﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
using System.Collections.Generic;
using System.IO;

using CE.User;
using CE.Global;
using CE.Database;
using CE.CarInsurance;
using CE.Mail;

public partial class carinsurance_ViewCINoMatchFoundTwo : System.Web.UI.Page
{
    int _currentRow = 0;
    private DateTime dateTimeNow = CE.Global.General.GetUTCDateTime();

    protected override void InitializeCulture()
    {
        String selectedCulture = CE.Global.General.SetCulture();
        base.InitializeCulture();
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session[CE.Global.General.UserId] == null)
        {
            Response.Redirect("~/SiteUserSecureLogin.aspx");
        }

        if (!IsPostBack)
        {
            IncludeScripeEnable(CE.Global.General.SetCulture());
            //For monthly Installment -- start
            ddlGGDiscount.Items.Clear();
            ddlGGDiscount.Items.Add(new ListItem(0 + " %", "0"));
            ddlNoofInstallments.Items.Clear();
            ddlNoofInstallments.Items.Add(new ListItem("3" + " " + Resources.CarInsurance.Installment, "3"));
            lblCreditCardAllowed.Text = "1. " + Resources.CarInsurance.BankK;
            lblCreditCardAllowed.ForeColor = System.Drawing.Color.Green;

            lblInterest.Text = Resources.CarInsurance.InterestFree;
            //For monthly Installment -- End

            if (Request.Params["calltype"] != null)
            {
                lblCallType.Text = Request.Params["calltype"].ToString();
                ShowCallTypeDesc();
            }
            else
            {
                Response.Redirect("~/SiteUserHome.aspx");
            }

            if (Request.Params["leadid"] != null && Request.Params["calltype"] != null
                && Request.Params["carid"] != null && Request.Params["custid"] != null)
            {
                Int64 _leadId = 0;
                Int16 _callType = 0;
                Int64 _carId = 0;
                Int64 _custId = 0;

                if (Int64.TryParse(Request.Params["leadid"].ToString(), out _leadId)
                    && Int16.TryParse(Request.Params["calltype"].ToString(), out _callType)
                    && Int64.TryParse(Request.Params["carid"].ToString(), out _carId)
                    && Int64.TryParse(Request.Params["custid"].ToString(), out _custId))
                {
                    //Call Type = 102 and 103 can be CarID and CustomerID ZERO
                    if (_carId == 0 && _custId == 0)
                    {
                        string _strCallMeId = "0";

                        if (Request.Params["callmeid"] != null)
                        {
                            _strCallMeId = Request.Params["callmeid"].ToString();
                        }

                        if (_callType == 103)
                        {
                            Response.Redirect("callme-newlead-quotes.aspx?leadid=" + _leadId.ToString() + "&callmeid=" + _strCallMeId + "&calltype=" + _callType.ToString() + "&carid=0" + "&custid=0");
                        }
                        else
                        {
                            Response.Redirect("~/carinsurance/ViewCICustomerCallNewSearch.aspx?leadid=" + _leadId.ToString() + "&callmeid=" + _strCallMeId + "&calltype=" + _callType.ToString());
                        }
                    }
                    else if (!ShowScreen(_leadId, _callType, _carId, _custId))
                    {
                        lblCallSessionName.Text = Resources.General.NORECORDFOUND;
                        ResetAll();
                    }
                    if (_custId > 0)
                    {
                        txtUserTypeId.Text = GetUserTypeId(_custId).ToString();
                    }
                }
                else
                {
                    Response.Redirect("~/SiteUserHome.aspx");
                }
            }
            else if (!ShowScreen())
            {
                if ((dateTimeNow.Hour >= 9 && dateTimeNow.Hour <= 10)
                    || (dateTimeNow.Hour >= 13 && dateTimeNow.Hour <= 14)
                    || (dateTimeNow.Hour >= 17))
                {
                    lblCallSessionName.Text += "<br/><br/>" + "Sorry, please try again later.<br/> You don't have any more follow up or call back.";
                }
                else
                {
                    lblCallSessionName.Text += "<br/><br/>" + Resources.General.NORECORDFOUND;
                    lblCallSessionName.Text += "<br/><br/>INVALID. NOT FOUND! CHECK CX IT TEAM.";
                }
                ResetAll();
            }
        }
    }

    public Int64 GetUserTypeId(Int64 CustomerId)
    {
        Int64 _result = 400;
        try
        {
            MyDatabase _db = new MyDatabase();
            string _strSelect = "SELECT UsrTypeId FROM tblCEUser WHERE CEID = " + CustomerId.ToString();

            DataTable _dtUsrTypeId = new DataTable("tblUsrTypeId");

            _dtUsrTypeId = _db.GetDataTable(_strSelect);

            if (_dtUsrTypeId != null && _dtUsrTypeId.Rows.Count > 0)
            {
                if (_dtUsrTypeId.Rows[0]["UsrTypeId"] != DBNull.Value)
                {
                    _result = Convert.ToInt64(_dtUsrTypeId.Rows[0]["UsrTypeId"].ToString());
                }
            }
        }
        catch (Exception Ex)
        {
        }
        return _result;
    }

    private void LoadControlData()
    {
        DateTime time = dateTimeNow;
        lblStartDateTime.Text = time.ToString("dd/MMM/yyyy hh:mm:ss tt"); //Don't use HTML tag inside text
        lblStartDayName.Text = "<b style='color:red;'>" + time.ToString("dddd") + " </b>";
        hplReRunQuote.Attributes.Add("onclick", "javascript:return confirm('" + Resources.General.ConfirmReRunQuoteMessage + "');");
        hplNewQuote.Attributes.Add("onclick", "javascript:return confirm('" + Resources.General.ConfirmRunNewQuoteMessage + "');");

        LoadBrokerProvider();
        LoadBrokerCoverType();

        DateTime _dtNow = dateTimeNow;

        for (int d = 0; d < 60; d++)
        {
            ddlEditCoverCommencementDate.Items.Add(new ListItem(_dtNow.ToString("dd/MMM/yyyy"), _dtNow.ToString("dd/MMM/yyyy")));
            _dtNow = _dtNow.AddDays(1);
        }

        ddlEditCoverCommencementDate.Text = dateTimeNow.ToString("dd/MMM/yyyy");
        lblEditCoverCommencementDate.Text = ddlEditCoverCommencementDate.Text;

        lblResetUrl.Text = Request.Url.ToString();
        ResetAll();
        txtAgentId.Text = Session[General.UserId].ToString();
        LoadAgentList();
        for (int i = 2012; i <= dateTimeNow.Year + 1; i++)
        {
            ddlTYear.Items.Add(new ListItem(i.ToString(), i.ToString()));
            ddlTYear.Text = dateTimeNow.Year.ToString();
            ddlTDay.Text = dateTimeNow.AddDays(1).ToString();
            ddlTMonth.Text = dateTimeNow.Month.ToString("00");
        }

        ddlCIMainCallStatus.Items.Clear();
        ddlCICallStatus.Items.Clear();
        rdoCallFinish.Checked = true;
        rdoCallFinish_CheckedChanged(null, null);

        if (ddlCIMainCallStatus.Items.Count > 0)
        {
            ddlCIMainCallStatus.SelectedIndex = 0;
            ddlCIMainCallStatus_SelectedIndexChanged(null, null);
        }
    }

    private void ShowCarPlateNumber(Int64 CECarID, Int64 CustomerID)
    {
        BrokerPremiumDB _db = new BrokerPremiumDB();
        string _carplateNumber = _db.GetCarPlate(CECarID, CustomerID);
        if (_carplateNumber != string.Empty)
        {
            txtEditLicensePlate.Text = _carplateNumber;
            lblEditLicensePlate.Text = _carplateNumber;
        }
    }

    private void ShowLastQuotationSendDate(Int64 CECarID, Int64 CustomerID)
    {
        BrokerPremiumDB _db = new BrokerPremiumDB();
        string _lastSendStatus = _db.GetLastQuotationSendDate(CECarID, CustomerID, 1);
        if (_lastSendStatus != string.Empty)
        {
            string[] strLastSendValues = _lastSendStatus.Split(',');
            lblSendQuotationMessage.Text = Resources.General.QuotationSent + " > " + strLastSendValues[0];
            txtConfirmEmail.Text = strLastSendValues[0];

            lblSendQuotationMessage.Text += " > " + Convert.ToDateTime(strLastSendValues[1]).ToString("dd/MMM/yyyy hh:mm tt");
            
        }
    }

    private void ShowLastOrderConfirmationSendDate(Int64 CECarID, Int64 CustomerID)
    {
        BrokerPremiumDB _db = new BrokerPremiumDB();
        string _lastSendStatus = _db.GetLastQuotationSendDate(CECarID, CustomerID, 3);
        if (_lastSendStatus != string.Empty)
        {
            string[] strLastSendValues = _lastSendStatus.Split(',');
            lblSendOrderConfirmationMessage.Text = "<br/>" + Resources.General.OrderConfirmationSent + " > " + strLastSendValues[0];
            txtConfirmEmail.Text = strLastSendValues[0];

            lblSendOrderConfirmationMessage.Text += " > " + Convert.ToDateTime(strLastSendValues[1]).ToString("dd/MMM/yyyy hh:mm tt");
            
        }
    }

    private string GetCallDuration()
    {
        DateTime _dtStartTime = Convert.ToDateTime(lblStartDateTime.Text);
        TimeSpan _duration = dateTimeNow - _dtStartTime;
        string _strMin = _duration.Minutes.ToString();
        string _strSec = _duration.Seconds.ToString();
        txtMinute.Text = _strMin;
        txtSecond.Text = _strSec;

        if (Convert.ToInt16(_strMin) < 10)
        {
            _strMin = "0" + _strMin;
        }

        if (Convert.ToInt16(_strSec) < 10)
        {
            _strSec = "0" + _strSec;
        }

        return _strMin + " : " + _strSec;
    }

    protected void ResetAll()
    {
        //txtCustomerID CAN NOT CLEAR
        txtCarId.Text = "";
        txtCarPolicyId.Text = "";
        hplReRunQuote.NavigateUrl = "";
        hplNewQuote.NavigateUrl = "";
        divLinks.Visible = false;

        lblCallStatusMessage.Text = "";
        
        
        tplResults.Visible = false;

        
        tplCallStatus.Visible = false;

        divCompletedQuoteDetails.Visible = false;
       
        tplCustomerPolicyDetail.Visible = false;

        
        tplCallHistory.Visible = false;

       
        tplEdit.Visible = true;

        
        tplPremiumList.Visible = false;

        btnReset.Visible = false;

        ResetCallStatus();
    }

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        txtCallStatusId.Text = "0";
        txtCarId.Text = "";
        txtCustomerId.Text = "";
       

        lblCallStatusMessage.Text = "";
        
       
        tplCallStatus.Visible = false;

        
        tplCustomerPolicyDetail.Visible = false;

        divCXBrokerPremium.Visible = false;
        
        hplPremiumDownLoad.Visible = false;
        hplPremiumDownLoad.NavigateUrl = "";
    }

    protected void btnCallStatus_Click(object sender, EventArgs e)
    {
        lblCallStatusMessage.Text = "";
        lblLastCallStatusMessage.Text = "";
        Page.Validate("callstatus");

        if (rdoCallBack.Checked)
        {
            int _callBackCount = 0;
            if (int.TryParse(txtCallBackCount.Text, out _callBackCount))
            {
                if (_callBackCount > 15)
                {
                    lblCallStatusMessage.Text = Resources.General.Callback + " (" + Resources.General.CallBackLimitMessage + ") " + Resources.General.FAIL + " " + dateTimeNow.ToString("dd/MMM/yyyy hh:mm:ss tt");
                    return;
                }
            }
        }

        if (Page.IsValid)
        {
            if (txtCarId.Text.Length > 0 && txtCustomerId.Text.Length > 0)
            {
                CallStatus callstatus = new CallStatus();
                CallStatusDB callstatusdb = new CallStatusDB();

                
                //CallType IS NOT USING ACTUALLY BECAUSE OF DUPLICATE LEADID
                callstatus = callstatusdb.GetCallStatus(Convert.ToInt64(lblAgentLeadID.Text), Convert.ToInt32(lblCallType.Text));

                if (callstatus == null)
                {
                    callstatus = new CallStatus();
                }

               

                callstatus.CarId = Convert.ToInt64(txtCarId.Text);
                if (Session[CE.Global.General.CarResultId] != null)
                {
                    callstatus.CarResultId = Convert.ToInt64(Session[CE.Global.General.CarResultId].ToString());
                }
                callstatus.CustomerId = Convert.ToInt64(txtCustomerId.Text);
                callstatus.AgentId = Convert.ToInt64(txtAgentId.Text);

                callstatus.AgentLeadId = Convert.ToInt64(lblAgentLeadID.Text);
                if (rdoCallFinish.Checked)
                {
                    callstatus.CallFinishType = 1;
                }
                else if (rdoCallBack.Checked)
                {
                    callstatus.CallBackDateTime = Convert.ToDateTime(txtCallBackDateTime.Text);
                    callstatus.CallBackAgentID = Convert.ToInt64(ddlCBAgentList.Text);
                    callstatus.CallFinishType = 2;
                }
                else if (rdoFollowUp.Checked)
                {
                    callstatus.CallFinishType = 3;
                }

                if (ddlCIMainCallStatus.Text == "7" && ddlCICallStatus.Text == "10")
                {
                    callstatus.CallBackDateTime = Convert.ToDateTime(txtCallBackDateTime.Text);
                    callstatus.CallBackAgentID = Convert.ToInt64(Session[General.UserId].ToString());
                }

                callstatus.MainCallStatusTypeID = Convert.ToInt32(ddlCIMainCallStatus.Text);

                callstatus.CallStatusTypeID = Convert.ToInt32(ddlCICallStatus.Text);
                callstatus.CallTypeId = Convert.ToInt32(lblCallType.Text);
                callstatus.StartDateTime = Convert.ToDateTime(lblStartDateTime.Text);
                callstatus.Remark = Server.HtmlEncode(txtCallStatus.Text);
                callstatus.CXCRMId = callstatusdb.Insert(callstatus);

                if (callstatus.CXCRMId > 0)
                {
                    if (txtCXCRMId.Text.Length > 0 && txtCXCRMId.Text != "0")
                    {
                        lblCallStatusMessage.Text = Resources.General.UPDATE + " " + dateTimeNow.ToString("dd/MMM/yyyy hh:mm:ss tt");
                    }
                    else
                    {
                        txtCXCRMId.Text = callstatus.CXCRMId.ToString();
                        lblCallStatusMessage.Text = Resources.General.SUCCESS + " " + dateTimeNow.ToString("dd/MMM/yyyy hh:mm:ss tt");
                    }

                    lblCallDurationTimer.Visible = false;


                   

                    lblCallStatusMessage.Text += ", " + Resources.General.CallDuration + ": " + GetCallDuration();
                    btnNext.Visible = true;
                    btnCallStatus.Enabled = false;
                }
                else
                {
                    lblCallStatusMessage.Text = Resources.General.FAIL + " " + dateTimeNow.ToString("dd/MMM/yyyy hh:mm:ss tt");
                }
                callstatus = null;
                callstatusdb = null;
            }
            else
            {
                lblCallStatusMessage.Text = Resources.General.FAIL;
            }
        }
    }

    protected void btnSubmitPremium_Click(object sender, EventArgs e)
    {
        if (Convert.ToInt32(lblCarMoreDetailID.Text) > 0)
        {
            btnSubmitPremium.Enabled = false;
            btnNewPremium.Enabled = false;
            btnEditSubmit.Enabled = false;
            lblPremiumMessage.Text = Resources.General.NonGGFoundAppDetailSubmission;
            lblPremiumMessage.ForeColor = System.Drawing.Color.Red;
            ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('" + Resources.General.NonGGFoundAppDetailSubmission + "');", true);
            return;
        }

        if (chkCompanyStaff.Checked && Session[General.UserRole].ToString() == "100")
        {
            lblPremiumMessage.Text = "You are NOT allowed to update this premium for Company Staff.";
            ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('You are NOT allowed to update this premium for Company Staff.');", true);
            return;
        }

        DateTime _dtCoverCommDate = dateTimeNow;
        if (DateTime.TryParse(lblEditCoverCommencementDate.Text, out _dtCoverCommDate))
        {
            DateTime _dtNow = new DateTime(dateTimeNow.Year, dateTimeNow.Month, dateTimeNow.Day);

            if (DateTime.Compare(_dtNow, _dtCoverCommDate) > 0)
            {
                lblPremiumError.Text = Resources.General.CommencementCheck;
                ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('" + Resources.General.CommencementCheck + "');", true);
                return;
            }
            else
            {
                lblEditCoverCommencementDateCaption.ForeColor = System.Drawing.Color.Gray;
                lblEditCoverCommencementDateMessage.Text = string.Empty;
            }
        }
        else
        {
            lblPremiumError.Text = Resources.General.CommencementCheck;
            ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('" + Resources.General.CommencementCheck + "');", true);
            return;
        }

        float _sumInsured = 0.0f;
        if (!float.TryParse(txtOwnDamage.Text, out _sumInsured))
        {
            lblPremiumError.Text = Resources.General.SumInsurredNotValid;
            ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('" + Resources.General.SumInsurredNotValid + "');", true);
            return;
        }

        decimal _InstalmentPremiumWOD = 0;
        if (!decimal.TryParse(lblTotalGrossPremiumWOD.Text, out _InstalmentPremiumWOD))
        {
            _InstalmentPremiumWOD = 0;
        }
        if (_InstalmentPremiumWOD <= 0 && ddlPaymentOption.Text == "IP")
        {
            lblPremiumError.Text = Resources.General.PayMsg_NoInstallment;
            ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('" + Resources.General.PayMsg_NoInstallment + "');", true);
            return;
        }
        Page.Validate("premium");

        if ((Convert.ToInt32(txtPremiumId.Text) > 0) || (Convert.ToInt32(txtPremiumId.Text) <= 0 && grvPremiumList.Rows.Count < 4))
        {
            if (IsValid)
            {
                DataSet _dsValid = new DataSet();
                _dsValid = GetPaymentsList();
                if (_dsValid != null && _dsValid.Tables.Count > 0)
                {
                    if (_dsValid.Tables[0].Rows.Count > 0)
                    {
                        lblPremiumError.Text = Resources.General.PayMsg_AlreadyhaveInstallmentPayments;
                        ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('" + Resources.General.PayMsg_AlreadyhaveInstallmentPayments + "');", true);
                        return;
                    }
                    if (_dsValid.Tables.Count > 1 && _dsValid.Tables[1].Rows.Count > 0 && ddlPaymentOption.Text == "IP")
                    {
                        lblPremiumError.Text = Resources.General.PayMsg_AlreadyhaveAnnualPayments;
                        ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('" + Resources.General.PayMsg_AlreadyhaveAnnualPayments + "');", true);
                        return;
                    }
                }

                Int64 _result = 0;
                string _ProductType = "CIN";
                BrokerPremium _brokerPremium = new BrokerPremium();
                BrokerPremiumDB _brokerPremiumdb = new BrokerPremiumDB();

               

                _brokerPremium.CXBrokerPremiumId = Convert.ToInt64(txtPremiumId.Text);
                _brokerPremium.CXBrokerProviderId = Convert.ToInt64(ddlBrokerProvider.Text);
                _brokerPremium.ProviderCoverTypeId = Convert.ToInt64(ddlBrokerCoverType.Text);
                _brokerPremium.CECarId = Convert.ToInt64(txtCarId.Text);
                _brokerPremium.CustomerId = Convert.ToInt64(txtCustomerId.Text);
                _brokerPremium.AgentId = Convert.ToInt64(txtAgentId.Text);
                _brokerPremium.Premium = Convert.ToSingle(txtNetPremium.Text);

                _brokerPremium.SelectedStatus = chkSelected.Checked;
                //_brokerPremium.Package = txtPremiumPackage.Text;
                _brokerPremium.WorkShop = ddlGarageType.Text;
                _brokerPremium.ProductType = _ProductType;
                _brokerPremium.TotalVMI = Convert.ToSingle(txtGrossPremium.Text);

               

                _brokerPremium.IsIncludeCMI = chkCTPL.Checked;

                if (chkCTPL.Checked)
                {
                    _brokerPremium.TotalCMI = Convert.ToSingle(txtCTPL.Text);
                }
                else
                {
                    _brokerPremium.TotalCMI = 0;
                }
                _brokerPremium.DiscountPercentage = Convert.ToInt16(ddlDiscountPercentage.Text);


                _brokerPremium.SumInsured = Convert.ToInt32(_sumInsured.ToString("#0"));
                if (_sumInsured > 1000)
                {
                    _brokerPremium.OwnDamage = _sumInsured.ToString("#,000");
                }
                else
                {
                    _brokerPremium.OwnDamage = _sumInsured.ToString("#0");
                }

                _brokerPremium.AnnualPremium = Convert.ToSingle(txtAnnualPremium.Text);
                
                _brokerPremium.TPPD = txtTPPD.Text;
                _brokerPremium.TPBIP = txtTPBIP.Text;
                _brokerPremium.TPBIA = txtTPBIA.Text;
                _brokerPremium.DEC = txtDeductible.Text;
                _brokerPremium.FireTheft = txtFireTheft.Text;

                _brokerPremium.PADriver = txtPA.Text;
                _brokerPremium.MedicalExpense = txtMED.Text;
                _brokerPremium.BailBound = txtBailBond.Text;

                _brokerPremium.Info1 = lblQRefNo.Text;
                _brokerPremium.Info2 = txtEditLicensePlate.Text;
                _brokerPremium.Info3 = ddlVehicleBodyType.Text;
                _brokerPremium.Info4 = chkCompanyStaff.Checked ? "1" : "0";
                _brokerPremium.Info5 = txtFloodCoverAmount.Text;
                _brokerPremium.Info6 = chkNamedDriver.Checked ? "1" : "0";
                _brokerPremium.Info7 = txtAccModCost.Text;
                _brokerPremium.Info8 = txtPremiumChangeComments.Text;
                

                _brokerPremium.PaymentOption = "FP";
                if (ddlPaymentOption.Text != "-1")
                {
                    _brokerPremium.PaymentOption = ddlPaymentOption.Text;
                }
                _brokerPremium.NoofInstallment = Convert.ToInt32(ddlNoofInstallments.Text);
                _brokerPremium.Bank = ddlCreditCard.Text;
                float _ipFAPremiumWD = 0.0f;
                if (!float.TryParse(lblTotalGrossPremiumWD.Text, out _ipFAPremiumWD))
                {
                    _ipFAPremiumWD = 0.0f;
                }
                
                _brokerPremium.IPFinalAnnualPremiumWD = _ipFAPremiumWD;
                _brokerPremium.InstallmentAmountWD = Convert.ToSingle(lblFirstInstallmentWD.Text);
                _brokerPremium.LastInstallmentAmountWD = Convert.ToSingle(lblLastInstallmentWD.Text);
                _brokerPremium.IPFinalAnnualPremiumWOD = Convert.ToSingle(lblTotalGrossPremiumWOD.Text);
                _brokerPremium.InstallmentAmountWOD = Convert.ToSingle(lblFirstInstallmentWOD.Text);
                _brokerPremium.LastInstallmentAmountWOD = Convert.ToSingle(lblLastInstallmentWOD.Text);

                if (ddlPaymentOption.Text == "IP")
                {
                    if (_ipFAPremiumWD > 0)
                    {
                        _brokerPremium.FinalAnnualPremium = _brokerPremium.IPFinalAnnualPremiumWD;
                    }
                    else
                    {
                        _brokerPremium.FinalAnnualPremium = _brokerPremium.IPFinalAnnualPremiumWOD;
                    }
                    _brokerPremium.FinalAnnualPremiumNoDisc = _brokerPremium.IPFinalAnnualPremiumWOD;

                    _brokerPremium.FinalAnnualPremiumWD = Convert.ToSingle(txtFinalAnnualPremium.Text);
                    _brokerPremium.FinalAnnualPremiumWOD = Convert.ToSingle(txtFinalAnnualPremiumNoDisc.Text);
                }
                else
                {
                    _brokerPremium.FinalAnnualPremium = Convert.ToSingle(txtFinalAnnualPremium.Text);
                    _brokerPremium.FinalAnnualPremiumNoDisc = Convert.ToSingle(txtFinalAnnualPremiumNoDisc.Text);

                    _brokerPremium.FinalAnnualPremiumWD = Convert.ToSingle(txtFinalAnnualPremium.Text);
                    _brokerPremium.FinalAnnualPremiumWOD = Convert.ToSingle(txtFinalAnnualPremiumNoDisc.Text);
                }

                _result = _brokerPremiumdb.Insert(_brokerPremium);
                if (_result > 0)
                {
                    if (chkSelected.Checked)
                    {
                        lblSelectedRefNo.Text = lblQRefNo.Text;
                    }
                    chkConfirmEmail.Checked = false;
                    chkConfirmEmail_CheckedChanged(sender, e);
                    lblSendQuotationMessage.Text = string.Empty;

                    txtPremiumId.Text = _result.ToString();
                    lblPremiumError.Text = "";
                    lblPremiumMessage.Text = "Successfully Updated";

                    grvPremiumList.DataBind();
                    if (grvPremiumList.Rows.Count > 0)
                    {
                        btnPremiumDownload.Visible = true;
                        lblAppStatusMessage.Text = "( " + grvPremiumList.Rows.Count.ToString() + " ) record(s) found.";
                    }
                    else
                    {
                        lblAppStatusMessage.Text = "No records found.";
                        hplPremiumDownLoad.Visible = false;
                    }
                    hplPremiumDownLoad.NavigateUrl = "PremiumDownload.aspx?carid=" + txtCarId.Text;
                }
                else
                {
                    txtPremiumId.Text = "0";
                    lblPremiumError.Text = "Updated Failed";
                    lblPremiumMessage.Text = "";
                }
            }
        }
        else
        {
            lblPremiumError.Text = "Please create only MAX 4 quotations!";
        }
    }

    public DataSet GetPaymentsList()
    {
        DataSet _ds = new DataSet();
        if (txtCarId.Text != string.Empty && txtCarId.Text != "0")
        {
            MyDatabase _db = new MyDatabase("GG_CRMDBConnectionString");
            SortedList _sPara = new SortedList();
            string _spName = "sprocCXCRMPaymentSelectItemListByCECarId";
            _sPara.Add("@CECarId", Convert.ToInt64(txtCarId.Text.Trim()));
            _ds = _db.GetDataSet(_spName, _sPara);
        }
        return _ds;
    }

    private bool ShowScreen(Int64 AgentLeadID, Int16 CallType, Int64 CarID, Int64 CustomerID)
    {
        //DIFFERENT - NON-GG PACKAGES
        //Car ID and Customer ID got from Query String

        bool _retValue = false;
        try
        {
            if (CustomerID > 0)
            {
                txtUserTypeId.Text = GetUserTypeId(CustomerID).ToString();

                if (txtUserTypeId.Text == "1001")
                {
                    CarUserAccount _account = new CarUserAccount();
                    CarUserAccountDB _accountDB = new CarUserAccountDB();

                    _account = _accountDB.GetAccount(Convert.ToInt64(CustomerID));

                    if (_account != null)
                    {
                        if (_account.Status == false)
                        {
                            //REDIRECT
                            _account = null;
                            _accountDB = null;

                            hplReRunQuote.NavigateUrl = "callme-newlead-quotes.aspx?leadid=" + AgentLeadID.ToString() + "&callmeid=" + "0" + "&calltype=" + CallType.ToString() + "&carid=" + CarID.ToString() + "&custid=" + CustomerID;
                            Response.Redirect(hplReRunQuote.NavigateUrl);
                        }
                    }
                }
            }

            string _spName = "sprocCXCRMGetCarDetailSelectSingleItemByAgentLeadID";
            MyDatabase _db = new MyDatabase();
            DataTable _dtCarDetail = new DataTable("tblCar");
            SortedList _paraList = new SortedList();
            _paraList.Add("@AgentLeadID", AgentLeadID);
            _paraList.Add("@CallType", lblCallType.Text);
            _paraList.Add("@LangOption", lblLangOption.Text);
            _dtCarDetail = _db.GetDataTableBySP(_spName, _paraList);
            if (_dtCarDetail != null && _dtCarDetail.Rows.Count > 0)
            {

                LoadControlData();

                lblAgentLeadID.Text = _dtCarDetail.Rows[0][0].ToString();
                txtCarId.Text = CarID.ToString();
                txtCustomerId.Text = CustomerID.ToString();
                

                if (lblCallType.Text == "101" || lblCallType.Text == "102")
                {
                    txtCallMeId.Text = _dtCarDetail.Rows[0][5].ToString();
                }

                
                tplCarList.Visible = true;

                gvCarDetailList.DataBind();

                if (Session[General.BuyNowCarID] != null)
                {
                    SetGVCarDetailSelectedIndex(Convert.ToInt64(Session[General.BuyNowCarID].ToString()));
                }
                else
                {
                    SetGVCarDetailSelectedIndex(Convert.ToInt64(txtCarId.Text));
                }

                
                if (lblCallType.Text == "101" || lblCallType.Text == "102")
                {
                    lblCallSessionName.Text += "<td>" + Resources.CarInsurance.CarId + "</td><td><b style='color:red;'>" + _dtCarDetail.Rows[0][2].ToString() + "</b></td>";
                    lblCallSessionName.Text += "<td><b style='color:blue;'> CALL ME ID</td><td>" + _dtCarDetail.Rows[0][5].ToString() + "</b></td>";
                    lblCallSessionName.Text += "<td>" + Resources.CarInsurance.CallTime + "</td><td><b style='color:green;'>" + _dtCarDetail.Rows[0][7].ToString() + "</b></td>";
                    lblCallSessionName.Text += "<td>" + Resources.CarInsuranceResultPage.Insurer + "</td><td><b style='color:blue;'>" + _dtCarDetail.Rows[0][10].ToString() + "</b></td>";
                    lblCallSessionName.Text += "<td>" + Resources.General.Requestedon + "</td><td><b style='color:red;'>" + Convert.ToDateTime(_dtCarDetail.Rows[0][8].ToString()).ToString("dd/MMM/yyyy hh:mm:ss tt") + "</b></td></tr>";
                    lblCallSessionName.Text += "</table>";
                }
                else
                {
                    lblCallSessionName.Text += "</tr></table>";
                }


                ShowLastQuotationSendDate(CarID, CustomerID);
                ShowLastOrderConfirmationSendDate(CarID, CustomerID);

                CheckApplicationStatus();

                _retValue = true;
            }
            else
            {
                _retValue = false;
            }
        }
        catch (Exception Ex)
        {
            _retValue = false;
            lblCallSessionName.Text += "<br/><b style='color:red;'>" + Resources.General.ERROR + "</b>: at ShowScreen(Int64 AgentLeadID, Int16 CallType)<br/>" + Ex.Message + "<br/><br/>" + Ex.StackTrace;
            
        }

        return _retValue;
    }

    private bool ShowScreen()
    {
        bool _retValue = false;
        try
        {
            string _spName = "sprocCXCRMGetCarDetailSelectSingleItem";
            MyDatabase _db = new MyDatabase();
            DataTable _dtCarDetail = new DataTable("tblCar");
            SortedList _paraList = new SortedList();
            _paraList.Add("@AgentID", Session[General.UserId].ToString());
            _paraList.Add("@CallType", lblCallType.Text);
            _paraList.Add("@LangOption", lblLangOption.Text);

            _dtCarDetail = _db.GetDataTableBySP(_spName, _paraList);
            if (_dtCarDetail != null && _dtCarDetail.Rows.Count > 0)
            {
                string _agentLeadID = _dtCarDetail.Rows[0][0].ToString();

                string _carID = _dtCarDetail.Rows[0][2].ToString();

                string _customerID = _dtCarDetail.Rows[0][1].ToString();

                if (_carID == "0" && _customerID == "0")
                {
                    if (_dtCarDetail.Rows[0][5] != DBNull.Value && Convert.ToInt32(_dtCarDetail.Rows[0][5].ToString()) > 0)
                    {
                        Response.Redirect("~/carinsurance/ViewCICustomerCallNewSearch.aspx?leadid=" + _agentLeadID + "&callmeid=" + _dtCarDetail.Rows[0][5].ToString() + "&calltype=" + _dtCarDetail.Rows[0][6].ToString());
                    }
                    else
                    {
                        if (_dtCarDetail.Rows[0][6] != DBNull.Value && _dtCarDetail.Rows[0][6].ToString() == "103")
                        {
                            Response.Redirect("~/carinsurance/offline/callme-newlead-quotes.aspx?leadid=" + _agentLeadID + "&callmeid=0&calltype=" + _dtCarDetail.Rows[0][6].ToString() + "&carid=0&custid=0");
                        }
                        else
                        {
                            lblCallSessionName.Text += "<br/>" + Resources.General.CallMeBack + " - " + Resources.General.FAIL;
                        }
                    }
                }
                else
                {
                    if (Convert.ToInt64(_customerID) > 0)
                    {
                        txtUserTypeId.Text = GetUserTypeId(Convert.ToInt64(_customerID)).ToString();
                    }
                    Int16 _usrTypeID = 400;
                    Int16 _callTypeID = Convert.ToInt16(_dtCarDetail.Rows[0][6].ToString());

                    if (_callTypeID == 100)
                    {
                        _usrTypeID = Convert.ToInt16(_dtCarDetail.Rows[0][7].ToString());
                    }

                    if (_usrTypeID == 1001)
                    {
                        CarUserAccount _account = new CarUserAccount();
                        CarUserAccountDB _accountDB = new CarUserAccountDB();

                        _account = _accountDB.GetAccount(Convert.ToInt64(_customerID));

                        if (_account != null)
                        {
                            if (_account.Status == false)
                            {
                                //REDIRECT
                                _account = null;
                                _accountDB = null;

                                hplReRunQuote.NavigateUrl = "callme-newlead-quotes.aspx?leadid=" + _agentLeadID + "&callmeid=" + "0" + "&calltype=" + "100" + "&carid=" + _carID + "&custid=" + _customerID;
                                Response.Redirect(hplReRunQuote.NavigateUrl);
                            }
                        }
                    }

                    LoadControlData();

                    lblAgentLeadID.Text = _agentLeadID;

                    txtCarId.Text = _carID;

                    txtCustomerId.Text = _customerID;

                    lblCallType.Text = _dtCarDetail.Rows[0][6].ToString();

                    ShowCallTypeDesc();

                    if (lblCallType.Text == "101" || lblCallType.Text == "102")
                    {
                        txtCallMeId.Text = _dtCarDetail.Rows[0][5].ToString();
                    }

                   
                    tplCarList.Visible = true;

                    gvCarDetailList.DataBind();

                    if (Session[General.BuyNowCarID] != null)
                    {
                        SetGVCarDetailSelectedIndex(Convert.ToInt64(Session[General.BuyNowCarID].ToString()));
                    }
                    else
                    {
                        SetGVCarDetailSelectedIndex(Convert.ToInt64(_dtCarDetail.Rows[0][2].ToString()));
                    }

                    if (lblCallType.Text == "101" || lblCallType.Text == "102")
                    {
                        lblCallSessionName.Text += "<td>" + Resources.CarInsurance.CarId + "</td><td><b style='color:red;'>" + _dtCarDetail.Rows[0][2].ToString() + "</b></td>";
                        lblCallSessionName.Text += "<td><b style='color:blue;'> CALL ME ID</td><td>" + _dtCarDetail.Rows[0][5].ToString() + "</b></td>";
                        lblCallSessionName.Text += "<td>" + Resources.CarInsurance.CallTime + "</td><td><b style='color:green;'>" + _dtCarDetail.Rows[0][7].ToString() + "</b></td>";
                        lblCallSessionName.Text += "<td>" + Resources.CarInsuranceResultPage.Insurer + "</td><td><b style='color:blue;'>" + _dtCarDetail.Rows[0][10].ToString() + "</b></td>";
                        lblCallSessionName.Text += "<td>" + Resources.General.Requestedon + "</td><td><b style='color:red;'>" + Convert.ToDateTime(_dtCarDetail.Rows[0][8].ToString()).ToString("dd/MMM/yyyy hh:mm:ss tt") + "</b></td></tr>";
                        lblCallSessionName.Text += "</table>";
                    }
                    else
                    {
                        lblCallSessionName.Text += "</tr></table>";
                    }

                    ShowLastQuotationSendDate(Convert.ToInt64(txtCarId.Text), Convert.ToInt64(txtCustomerId.Text));
                    ShowLastOrderConfirmationSendDate(Convert.ToInt64(txtCarId.Text), Convert.ToInt64(txtCustomerId.Text));

                    CheckApplicationStatus();

                    _retValue = true;
                }
            }
            else
            {
                _retValue = false;
            }
        }
        catch (Exception Ex)
        {
            _retValue = false;
            lblCallSessionName.Text += "<br/><b style='color:red;'>" + Resources.General.ERROR + "</b>: at ShowScreen()<br/>" + Ex.Message + "<br/><br/>" + Ex.StackTrace;
           
        }

        return _retValue;
    }

    private void ShowCallTypeDesc()
    {
        if (lblCallType.Text == "100")
        {
           
            lblCallTypeDesc.Text = Resources.General.FirstFollowUpCall;
            lblLastCallStatusCaption.Text = Resources.General.FirstFollowUpCall + " - " + Resources.General.LastCallStatus;
        }
        else if (lblCallType.Text == "101")
        {
            lblCallTypeDesc.Text = Resources.General.CallMeRequest;
            lblLastCallStatusCaption.Text = Resources.General.CallMeRequest + " - " + Resources.General.LastCallStatus;
        }
        else if (lblCallType.Text == "102")
        {
            lblCallTypeDesc.Text = Resources.General.CallMeBack;
            lblLastCallStatusCaption.Text = Resources.General.CallMeBack + " - " + Resources.General.LastCallStatus;
        }
        else if (lblCallType.Text == "103") //102
        {
            lblCallTypeDesc.Text = Resources.General.CallDirect;
            lblLastCallStatusCaption.Text = Resources.General.CallDirect + " - " + Resources.General.LastCallStatus;
        }
        lblCallTypeDesc.Text += ShowQuoteFrom();
    }

    private string ShowQuoteFrom()
    {
        string QuoteFrom = "";
        if (Request.Params["carid"] != null)
        {
            Int64 CarId = 0;
            if (!Int64.TryParse(Request.Params["carid"].ToString(), out CarId))
            {
                CarId = 0;
            }
            MyDatabase _myDb = new MyDatabase();
            DataTable _dtQuoteFrom = new DataTable("tblQuoteFrom");
            _dtQuoteFrom = _myDb.GetDataTable(@"SELECT Info8 FROM TBLCARPOLICY WHERE CECARID = " + CarId.ToString());

            if (_dtQuoteFrom != null && _dtQuoteFrom.Rows.Count > 0)
            {
                if (_dtQuoteFrom.Rows[0]["Info8"] != DBNull.Value && _dtQuoteFrom.Rows[0]["Info8"].ToString() != string.Empty && _dtQuoteFrom.Rows[0]["Info8"].ToString().ToUpper() == "MOBILE")
                {
                    QuoteFrom = " (" + Resources.Menu.Mobile + ")";
                }
            }
        }
        return QuoteFrom;
    }

    protected void ShowCarAndCustomerDetails(Int64 CustomerID, Int64 CarID, Int64 CarPolicyID)
    {
        if (CustomerID > 0 && CarID > 0 && CarPolicyID > 0)
        {
            txtCustomerId.Text = CustomerID.ToString();
            txtCarId.Text = CarID.ToString();

            //POLICY ID IS ONLY NEEDED FOR RE-RUN QUOTE
            txtCarPolicyId.Text = CarPolicyID.ToString();

            txtCICallMeRemark.Visible = false;
            lblRefCarID.Text = CarID.ToString();

            //Checking Application Summary
            MyDatabase _myDb = new MyDatabase();
            SortedList _paraList = new SortedList();
            _paraList.Add("@CECarID", CarID);
            _paraList.Add("@CustomerID", CustomerID);
            DataTable _dtApp = new DataTable("tblApp");
            _dtApp = _myDb.GetDataTableBySP("sprocCXCRMNonGGApplicationStatusSelectItem", _paraList);
            if (_dtApp != null && _dtApp.Rows.Count > 0)
            {
                if (_dtApp.Rows[0]["Completed"].ToString() == "1")
                {
                    lblLastYearRefNo.Text = _dtApp.Rows[0]["QuoteRefNo"].ToString();
                    lblRenewalStaus.Text = "1";
                    btnRenewalQuote.Text = "Renewal Quote";
                    btnRenewalQuote.Visible = true;
                    divLinks.Visible = true;

                    //divCarDetailList.Visible = false;
                    tplCarList.Visible = false;

                    btnSendOrderConfirmation.Visible = false;
                    btnNewPremium.Visible = false;
                    btnSendQuotation.Visible = false;
                    txtConfirmEmail.Visible = false;
                    btnNewPremiumTwo.Visible = false;

                    if (Session[General.UserRole].ToString() == "100")
                    {
                        btnRenewalQuote.Enabled = false;
                    }
                }
            }

            if (btnRenewalQuote.Visible == false)
            {
                #region Check Selected And Completed

                Int64 _providerCompanyId = 0;
                DataTable _dtSeletedItem = new DataTable("tblSelect");
                _dtSeletedItem = _myDb.GetDataTable(@"SELECT P.INSURANCETYPE, P.GarageType, P.IsCTPL, S.* FROM TBLCARINSURANCESELECTITEMTH S
	                                                INNER JOIN TBLCARPOLICY P ON S.CARID = P.CECARID AND P.REFCEUSERID = S.REFCEUSERID 
                                                    Where S.CarID = " + txtCarId.Text + " And S.RefCEUserID = " + txtCustomerId.Text);

                if (_dtSeletedItem != null && _dtSeletedItem.Rows.Count > 0)
                {
                    _providerCompanyId = Convert.ToInt64(_dtSeletedItem.Rows[0]["ProviderCompanyID"].ToString());
                    //divResult.Visible = false;
                    tplResults.Visible = false;

                    float _totalVMI = Convert.ToSingle(_dtSeletedItem.Rows[0]["TotalVMI"].ToString());
                    SortedList _sqlParam = new SortedList();
                    _sqlParam.Add("@CarID", txtCarId.Text);
                    _sqlParam.Add("@ProviderCompanyID", _providerCompanyId.ToString());
                    DataTable _dtCompltedQuote = _myDb.GetDataTableBySP("sprocCarInsuranceTHCompletedUserSelectItem", _sqlParam);

                    if (_dtCompltedQuote != null && _dtCompltedQuote.Rows.Count > 0)
                    {
                        divCompletedQuoteDetails.Visible = true;

                        lblCQFullName.Text = _dtCompltedQuote.Rows[0]["Name"].ToString();
                        lblCQQuoteRefNo.Text = _dtCompltedQuote.Rows[0]["QuoteRefNo"].ToString();
                        //lblCQCustomerAddress.Text = _dtCompltedQuote.Rows[0]["CustAddress"].ToString();
                        lblCQPaymentType.Text = _dtCompltedQuote.Rows[0]["Payment"].ToString();

                        lblCQOrderRefNo.Text = _dtCompltedQuote.Rows[0]["OrderRefNo"].ToString();
                        lblCQPackageName.Text = _dtCompltedQuote.Rows[0]["CoverTypeDesc"].ToString();
                        lblCQPremiumAmount.Text = _dtCompltedQuote.Rows[0]["PAnnualPremium"].ToString();
                        lblCQCTPLStatus.Text = _dtCompltedQuote.Rows[0]["IsCTPL"].ToString();
                        
                        lblCQDateTime.Text = Convert.ToDateTime(_dtCompltedQuote.Rows[0]["ModifiedDate"].ToString()).ToString("dd-MMM-yyyy hh:mm:ss tt");
                        ClientScript.RegisterStartupScript(this.GetType(), "JS_CompletedQuoteAlert", "alert(' " + Resources.CarInsurance.ReferenceNo + ". \"" + lblCQQuoteRefNo.Text + "\" >> " + Resources.CarInsurance.CarId + ": " + txtCarId.Text + " - " + Resources.General.AppFromGGOnline + "" + "');", true);
                        

                        if (_dtCompltedQuote.Rows[0]["CarPlate"] != DBNull.Value)
                        {
                            txtEditLicensePlate.Text = _dtCompltedQuote.Rows[0]["CarPlate"].ToString().ToUpper();
                            lblEditLicensePlate.Text = _dtCompltedQuote.Rows[0]["CarPlate"].ToString().ToUpper();
                        }

                        ddlBrokerProvider.Text = _providerCompanyId.ToString();
                        ddlBrokerProvider_SelectedIndexChanged(null, null);
                        ddlBrokerCoverType.Text = _dtSeletedItem.Rows[0]["INSURANCETYPE"].ToString();
                       

                        if (txtPremiumId.Text == "0")
                        {
                            ddlGarageType.Text = _dtSeletedItem.Rows[0]["GarageType"].ToString();


                            if (_dtSeletedItem.Rows[0]["TPBIA"] != DBNull.Value)
                            {
                                txtTPBIA.Text = Convert.ToSingle(_dtSeletedItem.Rows[0]["TPBIA"].ToString()).ToString("#,000");
                            }
                            else
                            {
                                txtTPBIA.Text = "N/A";
                            }

                            if (_dtSeletedItem.Rows[0]["TPBIP"] != DBNull.Value)
                            {
                                txtTPBIP.Text = Convert.ToSingle(_dtSeletedItem.Rows[0]["TPBIP"].ToString()).ToString("#,000");
                            }
                            else
                            {
                                txtTPBIP.Text = "N/A";
                            }

                            if (_dtSeletedItem.Rows[0]["TPPD"] != DBNull.Value)
                            {
                                txtTPPD.Text = Convert.ToSingle(_dtSeletedItem.Rows[0]["TPPD"].ToString()).ToString("#,000");
                            }
                            else
                            {
                                txtTPPD.Text = "N/A";
                            }

                            if (_dtSeletedItem.Rows[0]["DEC"] != DBNull.Value)
                            {
                                txtDeductible.Text = Convert.ToSingle(_dtSeletedItem.Rows[0]["DEC"].ToString()).ToString("#0");
                            }

                            if (_dtSeletedItem.Rows[0]["PADriver"] != DBNull.Value)
                            {
                                txtPA.Text = Convert.ToSingle(_dtSeletedItem.Rows[0]["PADriver"].ToString()).ToString("#,000");
                            }
                            else
                            {
                                txtPA.Text = "N/A";
                            }

                            if (_dtSeletedItem.Rows[0]["BailBond"] != DBNull.Value)
                            {
                                txtBailBond.Text = Convert.ToSingle(_dtSeletedItem.Rows[0]["BailBond"].ToString()).ToString("#,000");
                            }
                            else
                            {
                                txtBailBond.Text = "N/A";
                            }

                            if (_dtSeletedItem.Rows[0]["MedExp"] != DBNull.Value)
                            {
                                txtMED.Text = Convert.ToSingle(_dtSeletedItem.Rows[0]["MedExp"].ToString()).ToString("#,000");
                            }
                            else
                            {
                                txtMED.Text = "N/A";
                            }

                            txtGrossPremium.Text = _totalVMI.ToString("#000.00");

                            float _totalCMI = 0.0f;
                            if (_dtCompltedQuote.Rows[0]["IsCTPL"] != DBNull.Value)
                            {
                                if (_dtCompltedQuote.Rows[0]["IsCTPL"].ToString().ToLower() == "yes")
                                {
                                    _totalCMI = Convert.ToSingle(_dtCompltedQuote.Rows[0]["CTPL"].ToString());
                                    chkCTPL.Checked = true;
                                }
                                else
                                {
                                    chkCTPL.Checked = false;
                                }
                            }

                           
                            txtGrossPremium_TextChanged(null, null);
                        }
                    }
                    else
                    {
                        ddlBrokerProvider.Text = _providerCompanyId.ToString();
                        ddlBrokerProvider_SelectedIndexChanged(null, null);
                        ddlBrokerCoverType.Text = _dtSeletedItem.Rows[0]["INSURANCETYPE"].ToString();
                        

                        if (txtPremiumId.Text == "0")
                        {
                            ddlGarageType.Text = _dtSeletedItem.Rows[0]["GarageType"].ToString();


                            if (_dtSeletedItem.Rows[0]["TPBIA"] != DBNull.Value)
                            {
                                txtTPBIA.Text = Convert.ToSingle(_dtSeletedItem.Rows[0]["TPBIA"].ToString()).ToString("#,000");
                            }
                            else
                            {
                                txtTPBIA.Text = "N/A";
                            }

                            if (_dtSeletedItem.Rows[0]["TPBIP"] != DBNull.Value)
                            {
                                txtTPBIP.Text = Convert.ToSingle(_dtSeletedItem.Rows[0]["TPBIP"].ToString()).ToString("#,000");
                            }
                            else
                            {
                                txtTPBIP.Text = "N/A";
                            }

                            if (_dtSeletedItem.Rows[0]["TPPD"] != DBNull.Value)
                            {
                                txtTPPD.Text = Convert.ToSingle(_dtSeletedItem.Rows[0]["TPPD"].ToString()).ToString("#,000");
                            }
                            else
                            {
                                txtTPPD.Text = "N/A";
                            }

                            if (_dtSeletedItem.Rows[0]["DEC"] != DBNull.Value)
                            {
                                txtDeductible.Text = Convert.ToSingle(_dtSeletedItem.Rows[0]["DEC"].ToString()).ToString("#0");
                            }

                            if (_dtSeletedItem.Rows[0]["PADriver"] != DBNull.Value)
                            {
                                txtPA.Text = Convert.ToSingle(_dtSeletedItem.Rows[0]["PADriver"].ToString()).ToString("#,000");
                            }
                            else
                            {
                                txtPA.Text = "N/A";
                            }

                            if (_dtSeletedItem.Rows[0]["BailBond"] != DBNull.Value)
                            {
                                txtBailBond.Text = Convert.ToSingle(_dtSeletedItem.Rows[0]["BailBond"].ToString()).ToString("#,000");
                            }
                            else
                            {
                                txtBailBond.Text = "N/A";
                            }

                            if (_dtSeletedItem.Rows[0]["MedExp"] != DBNull.Value)
                            {
                                txtMED.Text = Convert.ToSingle(_dtSeletedItem.Rows[0]["MedExp"].ToString()).ToString("#,000");
                            }
                            else
                            {
                                txtMED.Text = "N/A";
                            }

                            txtGrossPremium.Text = _totalVMI.ToString("#000.00");

                            float _totalCMI = 0.0f;
                            if (_dtSeletedItem.Rows[0]["IsCTPL"] != DBNull.Value)
                            {
                                if (_dtSeletedItem.Rows[0]["IsCTPL"].ToString().ToLower() == "true")
                                {
                                    _totalCMI = Convert.ToSingle(_dtSeletedItem.Rows[0]["TotalCMI"].ToString());
                                    chkCTPL.Checked = true;
                                }
                                else
                                {
                                    chkCTPL.Checked = false;
                                }
                            }

                            txtCTPL.Text = _totalCMI.ToString("#,000.00");
                            txtGrossPremium_TextChanged(null, null);
                        }
                    }


                }
                #endregion
            }
            else
            {
                divCompletedQuoteDetails.Visible = false;
            }

            #region Show Hide Links
            if (divCompletedQuoteDetails.Visible == false && btnRenewalQuote.Visible == false)
            {
                hplNewQuote.NavigateUrl = "callme-newlead-quotes.aspx?leadid=" + lblAgentLeadID.Text + "&callmeid=" + txtCallMeId.Text + "&calltype=" + lblCallType.Text + "&carid=0" + "&custid=" + txtCustomerId.Text;
                hplReRunQuote.NavigateUrl = "callme-newlead-quotes.aspx?leadid=" + lblAgentLeadID.Text + "&callmeid=" + txtCallMeId.Text + "&calltype=" + lblCallType.Text + "&carid=" + txtCarId.Text + "&custid=" + txtCustomerId.Text;

                ResultsQuotesDataBind();

                hplNewQuote.Visible = true;
                hplReRunQuote.Visible = true;
                btnRenewalQuote.Visible = false;

               
                tplEdit.Visible = true;
                
              
                tplPremiumList.Visible = true;

            
                tplResults.Visible = true;

                divLinks.Visible = true;

             
                tplCallHistory.Visible = true;

            }
            else
            {
                divLinks.Visible = true;
                hplNewQuote.NavigateUrl = "callme-newlead-quotes.aspx?leadid=" + lblAgentLeadID.Text + "&callmeid=" + txtCallMeId.Text + "&calltype=" + lblCallType.Text + "&carid=0" + "&custid=" + txtCustomerId.Text;
                hplNewQuote.Visible = true;
                hplReRunQuote.Visible = false;
                btnRenewalQuote.Visible = false;

              
                tplEdit.Visible = false;
                
            
                tplPremiumList.Visible = true;

                gvCarResult.DataSource = null;
                gvCarResult.DataBind();
                
              
                tplResults.Visible = false;

           
                tplCallHistory.Visible = true;
            }
            #endregion

            #region Show Customer and Car Details
            MyDatabase _db = new MyDatabase();

            //Customer Details
            string _strSelect = "select P.FirstName, P.SurName, P.DOB, P.Gender, C.Email, C.Mobile, O.TH Occupation from tblCEUsrProfile P "
                                + "INNER JOIN tblOccupationInfo O ON P.Occupation = O.OccupationId "
                                + "INNER JOIN tblCEContact C ON C.RefCEUserID = P.RefCEUserID "
                                + "Where P.RefCEUserId = " + txtCustomerId.Text;
            DataTable _dtSelect = new DataTable("dtSelect");
            _dtSelect = _db.GetDataTable(_strSelect);
            if (_dtSelect != null && _dtSelect.Rows.Count > 0)
            {
                lblName.Text = _dtSelect.Rows[0]["FirstName"].ToString();
                lblLastName.Text = _dtSelect.Rows[0]["SurName"].ToString();
                lblGender.Text = _dtSelect.Rows[0]["Gender"].ToString() == "M" ? "ชาย" : "หญิง";
                lblDOB.Text = Convert.ToDateTime(_dtSelect.Rows[0]["DOB"].ToString()).ToString("dd/MMM/yyyy");
                lblOccupation.Text = _dtSelect.Rows[0]["Occupation"].ToString();
                lblMobileNo.Text = _dtSelect.Rows[0]["Mobile"].ToString();
                lblRefMobile.Text = lblMobileNo.Text;
                lblEmailAddress.Text = _dtSelect.Rows[0]["Email"].ToString();
                txtConfirmEmail.Text = lblEmailAddress.Text;
              
                txtConfirmEmail.Enabled = true;
                btnSendQuotation.Enabled = true;


                lblRefEmail.Text = lblEmailAddress.Text;
            }


            _dtSelect = null;
            _dtSelect = new DataTable("dtSelect");
            bool _IsClaim = false;
            bool _IsAddDriver = false;
            string _vehicleType;
            DateTime _dtCoverCommDate = dateTimeNow;

           

            _strSelect = "SELECT CP.InsuranceType, CP.GarageType, CP.VehicleType, CP.SumInsured, CP.NCDPercent, CP.IsClaimLastYear, CP.IsCTPL,"
                + " CP.IsAddDriver, CP.NoOfDriver,  CP.CoverageCommenceDate, CP.Info6, CP.Info7, CP.ModifiedDate,CD.Info3 "
                + " FROM tblCarPolicy CP INNER JOIN tblCarDetailTH CD ON CD.CarId = CP.CECarId "
                + " WHERE CP.RefCEUserId = " + CustomerID.ToString() + " AND CP.CECarId= " + CarID.ToString();
            _dtSelect = _db.GetDataTable(_strSelect);
          

            if (_dtSelect != null && _dtSelect.Rows.Count > 0)
            {
                lblInsuranceType.Text = "";
                string _strInsType = _dtSelect.Rows[0]["InsuranceType"].ToString().Substring(0, 2);
                if (_strInsType == "10")
                {
                    lblInsuranceType.Text = "1";
                }
                else if (_strInsType == "11")
                {
                    lblInsuranceType.Text = "1+";
                }
                else if (_strInsType == "21")
                {
                    lblInsuranceType.Text = "2+";
                }
                else if (_strInsType == "30")
                {
                    lblInsuranceType.Text = "3";
                }
                else if (_strInsType == "31")
                {
                    lblInsuranceType.Text = "3+";
                }


                //Checking Last Year Application Summary
                if (_dtSelect.Rows[0]["Info6"] != DBNull.Value && _dtSelect.Rows[0]["Info6"].ToString() != string.Empty
                    && _dtSelect.Rows[0]["Info7"] != DBNull.Value && _dtSelect.Rows[0]["Info7"].ToString() != string.Empty)
                {
                    _paraList = new SortedList();
                    _paraList.Add("@CECarID", _dtSelect.Rows[0]["Info6"].ToString());
                    _paraList.Add("@CustomerID", CustomerID);
                    _dtApp = new DataTable("tblApp");
                    _dtApp = _db.GetDataTableBySP("sprocCXCRMNonGGApplicationStatusSelectItem", _paraList);
                    if (_dtApp != null && _dtApp.Rows.Count > 0)
                    {
                        if (_dtApp.Rows[0]["Completed"].ToString() == "1")
                        {
                            lblLastYearRefNo.Text = _dtSelect.Rows[0]["Info7"].ToString();
                            lblRenewalStatusMessage.Text = " - Renewal - Last Year Ref.No: " + _dtSelect.Rows[0]["Info7"].ToString();
                            lblCallTypeDesc.Text += " - Renewal";
                            lblRenewalStaus.Text = "2";
                            hplReRunQuote.Visible = false;
                            hplNewQuote.Visible = false;
                            btnRenewalQuote.Visible = true;
                            divLinks.Visible = true;
                            //divCarDetailList.Visible = false;
                            tplCarList.Visible = false;
                            txtEditLicensePlate.Text = _dtApp.Rows[0]["CarPlate"].ToString();
                            lblEditLicensePlate.Text = txtEditLicensePlate.Text;
                        }
                    }
                }

                
                lblGarageType.Text = _dtSelect.Rows[0]["GarageType"].ToString() == "1" ? Resources.CarInsurance.Garage_Authorized : Resources.CarInsurance.Garage_Dealer;
              
                _vehicleType = _dtSelect.Rows[0]["Info3"].ToString();
                switch (_vehicleType)
                {
                    case "110":
                        lblVehicleType.Text = Resources.CarInsurance.VehicleType_Private;
                        break;
                    case "120":
                        lblVehicleType.Text = Resources.CarInsurance.VehicleType_Commercial;
                        break;
                    case "320":
                        lblVehicleType.Text = Resources.CarInsurance.VehicleType_Pickup;
                        break;
                    default:
                        lblVehicleType.Text = Resources.CarInsurance.VehicleType_Private;
                        break;
                }
            

                string _strQuoteDate = _dtSelect.Rows[0]["ModifiedDate"].ToString();
                DateTime _dtQuoteDate = dateTimeNow;
                DateTime _dtCompareQuoteDate = dateTimeNow.AddMonths(-1);
                if (DateTime.TryParse(_strQuoteDate, out _dtQuoteDate))
                {
                    lblRefModifiedDateTime.Text = _dtQuoteDate.ToString("dd/MMM/yyyy hh:mm tt");
                    if (DateTime.Compare(_dtCompareQuoteDate, _dtQuoteDate) > 0)
                    {
                        lblQuoteDateTimeStatus.Text = "0";
                        lblQuoteDateTimeStatusMessage.Text = Resources.General.QuoteDateTimeOVER;
                        lblQuoteDateTimeStatusMessage.Font.Bold = true;
                        lblQuoteDateTimeStatusMessage.ForeColor = System.Drawing.Color.Red;
                    }
                    else
                    {
                        lblQuoteDateTimeStatus.Text = "1";
                        lblQuoteDateTimeStatusMessage.Text = Resources.General.QuoteDateTimeOK;
                        lblQuoteDateTimeStatusMessage.Font.Bold = true;
                        lblQuoteDateTimeStatusMessage.ForeColor = System.Drawing.Color.Green;
                    }
                }
                else
                {
                    lblQuoteDateTimeStatus.Text = "0";
                    lblQuoteDateTimeStatusMessage.Text = Resources.General.QuoteDateTimeNOTVALID;
                    lblQuoteDateTimeStatusMessage.Font.Bold = true;
                    lblQuoteDateTimeStatusMessage.ForeColor = System.Drawing.Color.Red;
                }

                lblSumInsured.Text = Convert.ToInt32(_dtSelect.Rows[0]["SumInsured"]).ToString("#,000");
              
                txtOwnDamage.Text = lblSumInsured.Text;

                lblNCD.Text = _dtSelect.Rows[0]["NCDPercent"].ToString() == "-1" ? "0" : _dtSelect.Rows[0]["NCDPercent"].ToString() + "%";
                ddlEditNCB.Text = _dtSelect.Rows[0]["NCDPercent"].ToString() == "-1" ? "0" : _dtSelect.Rows[0]["NCDPercent"].ToString();

                lblCTPL.Text = Convert.ToBoolean(_dtSelect.Rows[0]["IsCTPL"]) == true ? "ใช่" : "ไม่ต้องการ";
                _IsClaim = Convert.ToBoolean(_dtSelect.Rows[0]["IsClaimLastYear"].ToString());
                _IsAddDriver = Convert.ToBoolean(_dtSelect.Rows[0]["IsAddDriver"].ToString());
                string _coverCommDate = _dtSelect.Rows[0]["CoverageCommenceDate"].ToString();

                if (DateTime.TryParse(_coverCommDate, out _dtCoverCommDate))
                {
                    lblCoverCommencementDate.Text = _dtCoverCommDate.ToString("dd/MMM/yyyy");
                    if (DateTime.Compare(dateTimeNow, _dtCoverCommDate) > 0)
                    {
                        lblCommenceDateStatus.Text = "0";
                        lblCommenceDateStatusMessage.Text = Resources.General.CommencementOVER;
                        lblCommenceDateStatusMessage.Font.Bold = true;
                        lblCommenceDateStatusMessage.ForeColor = System.Drawing.Color.Red;

                        ListItem myItem = new ListItem(lblCoverCommencementDate.Text, lblCoverCommencementDate.Text);
                        
                        ddlEditCoverCommencementDate.Items.Insert(0, myItem);
                        ddlEditCoverCommencementDate.Items[0].Attributes.Add("style", "color:red;");

                        lblEditCoverCommencementDateCaption.Font.Bold = true;
                        lblEditCoverCommencementDateCaption.ForeColor = System.Drawing.Color.Red;
                        ClientScript.RegisterStartupScript(this.GetType(), "JS_ClosedCallAlert", "alert('" + Resources.General.CommencementCheck + "');", true);
                        lblEditCoverCommencementDateMessage.Text = Resources.General.CommencementCheck;
                    }
                    else
                    {
                        lblCommenceDateStatus.Text = "1";
                        lblCommenceDateStatusMessage.Text = Resources.General.CommencementOK;
                        lblCommenceDateStatusMessage.Font.Bold = true;
                        lblCommenceDateStatusMessage.ForeColor = System.Drawing.Color.Green;
                    }

                    ddlEditCoverCommencementDate.Text = lblCoverCommencementDate.Text;
                    lblEditCoverCommencementDate.Text = lblCoverCommencementDate.Text;
                }
                else
                {
                    lblCommenceDateStatus.Text = "0";
                    lblCommenceDateStatusMessage.Text = Resources.General.CommencementNOTVALID;
                    lblCommenceDateStatusMessage.Font.Bold = true;
                    lblCommenceDateStatusMessage.ForeColor = System.Drawing.Color.Red;
                }

                CheckQuoteStatus();

                if (_IsAddDriver == true)
                {
                    lblDriverCount.Text = _dtSelect.Rows[0]["NoOfDriver"].ToString();
                    ddlEditNamedDriver.Text = lblDriverCount.Text;
                    chkNamedDriver.Checked = true;
                }
                else
                {
                    lblDriverCount.Text = "0";
                    ddlEditNamedDriver.Text = "0";
                    chkNamedDriver.Checked = false;
                }

                lblClaimInfo.Text = _IsClaim == true ? "ใช่" : "ไม่มี";

                _dtSelect = null;
                _dtSelect = new DataTable("dtSelect");

                _strSelect = " Select CD.MakeModelDesc, CD.ManufactYear, CD.Info15, CD.Info16, CD.Info17, CD.Info18, CD.Info19, P.TH CurrentInsurer "
                            + " from tblCarDetailTH CD"
                            + " INNER JOIN tblPreInsurer P ON CAST(CD.Info1 AS INT) = P.PreInsurerId"
                            + " Where P.CompanyType = 1 And P.ServiceType = 100 AND CD.RefCEUserId = " + txtCustomerId.Text + " And CD.CarId= " + txtCarId.Text;
                _dtSelect = _db.GetDataTable(_strSelect);
                if (_dtSelect != null && _dtSelect.Rows.Count > 0)
                {
                    lblCarMakeModel.Text = _dtSelect.Rows[0]["MakeModelDesc"].ToString();
                    lblRegYear.Text = _dtSelect.Rows[0]["ManufactYear"].ToString();
                    lblCurrentInsurer.Text = _dtSelect.Rows[0]["CurrentInsurer"].ToString();

                    if (btnRenewalQuote.Visible == false || lblRenewalStaus.Text == "2")
                    {
                        
                        tplEdit.Visible = true;

                        if (_dtSelect.Rows[0]["Info15"] != DBNull.Value && _dtSelect.Rows[0]["Info15"].ToString() != string.Empty)
                        {
                            txtEditLicensePlate.Text = _dtSelect.Rows[0]["Info15"].ToString();
                            lblEditLicensePlate.Text = _dtSelect.Rows[0]["Info15"].ToString();
                        }

                        if (_dtSelect.Rows[0]["Info16"] != DBNull.Value && _dtSelect.Rows[0]["Info16"].ToString() != string.Empty)
                        {
                            ddlEditNCB.Text = _dtSelect.Rows[0]["Info16"].ToString();
                        }

                        if (_dtSelect.Rows[0]["Info17"] != DBNull.Value && _dtSelect.Rows[0]["Info17"].ToString() != string.Empty)
                        {
                            ddlEditNamedDriver.Text = _dtSelect.Rows[0]["Info17"].ToString();
                        }

                        

                        if (_dtSelect.Rows[0]["Info19"] != DBNull.Value && _dtSelect.Rows[0]["Info19"].ToString() != string.Empty)
                        {
                            ddlEditCoverCommencementDate.Text = _dtSelect.Rows[0]["Info19"].ToString();
                            lblEditCoverCommencementDate.Text = _dtSelect.Rows[0]["Info19"].ToString();
                        }


                    }
                    else
                    {
                       
                        tplEdit.Visible = true;
                    }
                }

              
                tplCustomerPolicyDetail.Visible = true;
            }



            _dtSelect = null;
            _dtSelect = new DataTable("dtSelect");

            _db = null;
            _dtSelect = null;
            #endregion

            #region Broker Premium
            grvPremiumList.DataBind();
            if (grvPremiumList.Rows.Count > 0)
            {
                string url = "PremiumDownload.aspx?carid=" + txtCarId.Text.ToString();// +"," + txtVehicleNumber.Text.ToString();
                hplPremiumDownLoad.NavigateUrl = url;
            }
            else
            {
                hplPremiumDownLoad.Visible = false;
                hplPremiumDownLoad.NavigateUrl = "";
            }

            divCXBrokerPremium.Visible = true;
            #endregion

            #region Call Status
         
            if (tplCustomerPolicyDetail.Visible)
            {
                divCXBrokerPremium.Visible = true;
                ddlCICallStatus.Enabled = true;
                
               
                tplCallStatus.Visible = true;

                txtCallBackCount.Text = GetCallBackCount();

                CallStatus CI_callstatus = new CallStatus();
                CallStatusDB CI_callstatusdb = new CallStatusDB();
                CI_callstatus = CI_callstatusdb.GetCallStatus(Convert.ToInt64(lblAgentLeadID.Text), Convert.ToInt32(lblCallType.Text));

                if (CI_callstatus != null)
                {
                    txtCXCRMId.Text = CI_callstatus.CXCRMId.ToString();

                    txtCallBackDateTime.Text = "0";

                    rdoCallFinish.Checked = false;
                    rdoCallBack.Checked = false;
                    rdoFollowUp.Checked = false;
                    lblCallSessionName.Text = "<table class='sTable'>";

                    if (CI_callstatus.CallFinishType == 1)
                    {
                        rdoCallFinish.Checked = true;

                        ClientScript.RegisterStartupScript(this.GetType(), "JS_ClosedCallAlert", "alert('" + Resources.General.LastCallStatus.ToUpper() + " : " + lblCallTypeDesc.Text + " - " + Resources.General.CLOSEDCALL + lblRenewalStatusMessage.Text + "');", true);

                        if (CI_callstatus.CallStatusTypeID == 10 && CI_callstatus.MainCallStatusTypeID == 7)
                        {
                            txtCallBackDateTime.Text = CI_callstatus.CallBackDateTime.ToString("dd/MMM/yyyy hh:mm tt");
                            DateTime _dtTargetDateTime = dateTimeNow;
                            if (DateTime.TryParse(txtCallBackDateTime.Text, out _dtTargetDateTime))
                            {
                                ddlTDay.Text = _dtTargetDateTime.Day.ToString("00");
                                ddlTMonth.Text = _dtTargetDateTime.Month.ToString("00");
                                ddlTYear.Text = _dtTargetDateTime.Year.ToString("0000");
                                ddlTHour.Text = _dtTargetDateTime.Hour.ToString("00");
                                ddlTMin.Text = _dtTargetDateTime.Minute.ToString("00");

                                lblCallSessionName.Text += "<tr><td><b style='color:red;'>" + Resources.General.CLOSEDCALL + " >> " + Resources.CarInsurance.NewCommencementDate + ":</b></td><td>" + CI_callstatus.CallBackDateTime.ToString("dd/MMM/yyyy") + "</td>";
                            }
                            else
                            {
                                txtCallBackDateTime.Text = "0";
                            }
                        }
                        else
                        {
                            lblCallSessionName.Text += "<tr><td><b style='color:red;'>" + Resources.General.CLOSEDCALL + "</b></td>";
                        }
                    }
                    else if (CI_callstatus.CallFinishType == 2)
                    {
                        rdoCallBack.Checked = true;
                        ddlCBAgentList.Text = CI_callstatus.CallBackAgentID.ToString();
                        txtCallBackDateTime.Text = CI_callstatus.CallBackDateTime.ToString("dd/MMM/yyyy hh:mm tt");
                        lblCallSessionName.Text += "<tr><td><b style='color:red;'>" + Resources.General.Callback.ToUpper() + "</b></td><td>" + txtCallBackDateTime.Text + "</td>";
                        ClientScript.RegisterStartupScript(this.GetType(), "JS_CallBackCallAlert", "alert('" + Resources.General.LastCallStatus.ToUpper() + " : " + lblCallTypeDesc.Text + " - " + Resources.General.Callback + lblRenewalStatusMessage.Text + " [" + txtCallBackDateTime.Text + "]');", true);
                        DateTime _dtTargetDateTime = dateTimeNow;
                        if (DateTime.TryParse(txtCallBackDateTime.Text, out _dtTargetDateTime))
                        {
                            ddlTDay.Text = _dtTargetDateTime.Day.ToString("00");
                            ddlTMonth.Text = _dtTargetDateTime.Month.ToString("00");
                            ddlTYear.Text = _dtTargetDateTime.Year.ToString("0000");
                            ddlTHour.Text = _dtTargetDateTime.Hour.ToString("00");
                            ddlTMin.Text = _dtTargetDateTime.Minute.ToString("00");
                        }
                        else
                        {
                            txtCallBackDateTime.Text = "0";
                        }
                    }
                    else if (CI_callstatus.CallFinishType == 3)
                    {
                        rdoFollowUp.Checked = true;
                        lblCallSessionName.Text += "<tr><td><b style='color:blue;'>" + Resources.General.FollowUp.ToUpper() + "</b></td>";
                        ClientScript.RegisterStartupScript(this.GetType(), "JS_FollowUpCallAlert", "alert('" + Resources.General.LastCallStatus.ToUpper() + " : " + lblCallTypeDesc.Text + " - " + Resources.General.FollowUp.ToUpper() + lblRenewalStatusMessage.Text + "');", true);
                    }

                    rdoCallFinish_CheckedChanged(null, null);
                    if (ddlCIMainCallStatus.Items.Count > 0)
                    {
                        ddlCIMainCallStatus.Text = CI_callstatus.MainCallStatusTypeID.ToString();
                        ddlCIMainCallStatus_SelectedIndexChanged(null, null);

                        if (ddlCICallStatus.Items.Count > 0)
                        {
                            ddlCICallStatus.Text = CI_callstatus.CallStatusTypeID.ToString();
                            ddlCICallStatus_SelectedIndexChanged(null, null);
                        }
                    }

                    txtCallStatus.Text = Server.HtmlDecode(CI_callstatus.Remark);
                    lblLastCallStatusMessage.Text = Resources.General.FOUND + " [" + Resources.General.LastDateTime + ": " + CI_callstatus.ModifiedDate.ToString("dd/MMM/yyyy hh:mm tt") + "]";
                }
                else
                {
                    lblLastCallStatusMessage.Text = Resources.General.NEW;
                    lblCallSessionName.Text = Resources.General.NEWCALLPENDING;
                    ClientScript.RegisterStartupScript(this.GetType(), "JS_NewCallPendingAlert", "alert('" + lblCallTypeDesc.Text + " - " + Resources.General.NEWCALLPENDING + lblRenewalStatusMessage.Text + "');", true);
                }

                CI_callstatus = null;
                CI_callstatusdb = null;
            }
            #endregion

            #region Call History
            lblCallHistoryFoundCount.Text = "0";
            gvCallHistory.DataBind();
            if (lblCallHistoryFoundCount.Text != "0")
            {
                ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('" + lblCallHistoryMessage.Text + "');", true);
            }
            #endregion

            CheckApplicationStatus();

        }
    }

    protected void btnRenewQuote_Click(object sender, EventArgs e)
    {
        try
        {
            if (Session[General.UserRole].ToString() == "100")
            {
                lblRenewalQuoteMessage.Text = Resources.Proposal.AccessDenied;
                ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('" + Resources.Proposal.AccessDenied + "');", true);
                return;
            }

            if (lblRenewalStaus.Text == "2" && Convert.ToInt32(lblCarMoreDetailID.Text) > 0)
            {
                btnSubmitPremium.Enabled = false;
                btnNewPremium.Enabled = false;
                btnEditSubmit.Enabled = false;
                lblPremiumMessage.Text = Resources.General.NonGGFoundAppDetailSubmission;
                lblPremiumMessage.ForeColor = System.Drawing.Color.Red;
                ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('" + Resources.General.NonGGFoundAppDetailSubmission + "');", true);
                return;
            }

            Int64 _agentLeadId = 0;

            if (!Int64.TryParse(lblAgentLeadID.Text, out _agentLeadId))
            {
                _agentLeadId = 0;
            }

            Int64 _customerId = 0;

            if (!Int64.TryParse(txtCustomerId.Text, out _customerId))
            {
                _customerId = 0;
            }

            Int64 _carId = 0;
            Int64 _outCarID = 0;

            if (!Int64.TryParse(txtCarId.Text, out _carId))
            {
                _carId = 0;
            }

            Int64 _callMeId = 0;
            

            Int64 _agentID = 0;

            if (!Int64.TryParse(txtAgentId.Text, out _agentID))
            {
                _agentID = 0;
            }

            LoadCallMeAgentLeads(_agentLeadId, _customerId, _carId, Convert.ToInt64(Session[CE.Global.General.UserId].ToString()), Convert.ToInt32(lblCallType.Text), _callMeId, out _agentLeadId, out _customerId, out _outCarID);

            if (_agentLeadId > 0)
            {
                string _strParameters = "leadid=" + _agentLeadId.ToString() + "&calltype=" + lblCallType.Text;
                _strParameters += "&custid=" + _customerId.ToString() + "&carid=" + _outCarID.ToString();

                if (_carId == _outCarID)
                {
                    if (lblRenewalStaus.Text == "1")
                    {
                        _strParameters += "&renew=1";
                    }
                    else if (lblRenewalStaus.Text == "2")
                    {
                        _strParameters += "&renew=2";
                    }
                    else
                    {
                        return;
                    }
                }
                else
                {
                    _strParameters += "&renew=2";
                }



                _strParameters += "&refno=" + lblLastYearRefNo.Text;
               

                if (_customerId > 0 && _carId > 0)
                {
                    if (lblRenewalStaus.Text == "1")
                    {
                        if (_carId == _outCarID)
                        {
                            Response.Redirect("~/carinsurance/offline/callme-newlead-quotes.aspx?" + _strParameters.ToString());
                        }
                        else
                        {
                            if (CheckCXBrokerPremiumCount(_outCarID, _customerId))
                            {
                                Response.Redirect("~/carinsurance/offline/ViewCINoMatchFound.aspx?" + _strParameters.ToString());
                            }
                            else
                            {
                                Response.Redirect("~/carinsurance/offline/callme-newlead-quotes.aspx?" + _strParameters.ToString());
                            }
                        }
                    }
                    else
                    {
                        Response.Redirect("~/carinsurance/offline/callme-newlead-quotes.aspx?" + _strParameters.ToString());
                    }
                }
                else
                {
                    lblRenewalQuoteMessage.Text = "Please try again later.";
                    lblRenewalQuoteMessage.Font.Bold = true;
                    lblRenewalQuoteMessage.ForeColor = System.Drawing.Color.Red;
                }
            }
        }
        catch (Exception Ex)
        {
            lblRenewalQuoteMessage.Text = Ex.Message;
            lblRenewalQuoteMessage.Font.Bold = true;
            lblRenewalQuoteMessage.ForeColor = System.Drawing.Color.Red;
        }
    }

    public bool CheckCXBrokerPremiumCount(Int64 CarID, Int64 CustomerID)
    {
        bool _Result = false;
        MyDatabase _db = new MyDatabase("GG_CRMDBConnectionString");
        SortedList _sPara = new SortedList();
        string _spName = "[sprocCXBrokerPremiumGetCount]";
        _sPara.Add("@CarID", CarID);
        _sPara.Add("@CustomerID", CustomerID);
        _sPara.Add("@ProductType", "CIN");

        object _objCount = _db.ExecuteScalarSP(_spName, _sPara);
        if (_objCount != null && Convert.ToInt32(_objCount) > 0)
        {
            _Result = true;
        }

        return _Result;
    }

    private void LoadCallMeAgentLeads(Int64 AgentLeadId, Int64 CustomerID, Int64 CarId, Int64 AgentId, Int32 CallTypeId, Int64 CallMeId, out Int64 outAgentLeadID, out Int64 outCustomerID, out Int64 outCarID)
    {
        string _spName = "sprocCXCRMAgentLeadDetailsSelectSingleItem";
        MyDatabase _db = new MyDatabase();
        DataTable _dtCallMeAgentLeads = new DataTable("tblCallMeAgentLeads");
        SortedList _paraList = new SortedList();
        _paraList.Add("@AgentLeadId", AgentLeadId);
        _paraList.Add("@CustomerID", CustomerID);
        _paraList.Add("@CarID", CarId);
        _paraList.Add("@AgentId", AgentId);
        _paraList.Add("@CallTypeId", CallTypeId);
        _paraList.Add("@CallMeId", CallMeId);
        _dtCallMeAgentLeads = _db.GetDataTableBySP(_spName, _paraList);

        outAgentLeadID = 0;
        outCustomerID = 0;
        outCarID = 0;
        if (_dtCallMeAgentLeads != null && _dtCallMeAgentLeads.Rows.Count > 0)
        {
            lblAgentLeadID.Text = _dtCallMeAgentLeads.Rows[0]["AgentLeadId"].ToString();
            txtCustomerId.Text = _dtCallMeAgentLeads.Rows[0]["CustomerId"].ToString();
            txtCarId.Text = _dtCallMeAgentLeads.Rows[0]["CarId"].ToString();
            txtCallMeId.Text = _dtCallMeAgentLeads.Rows[0]["CallMeId"].ToString();
            lblCallType.Text = _dtCallMeAgentLeads.Rows[0]["CallType"].ToString();

            outAgentLeadID = Convert.ToInt64(lblAgentLeadID.Text);
            outCustomerID = Convert.ToInt64(txtCustomerId.Text);
            outCarID = Convert.ToInt64(txtCarId.Text);
        }
        
    }

    private void ResetCallStatus()
    {
        rdoCallFinish.Checked = true;
        rdoFollowUp.Checked = false;
        rdoCallBack.Checked = false;
        rdoCallFinish_CheckedChanged(null, null);
        ddlCIMainCallStatus.SelectedIndex = 0;
        ddlCIMainCallStatus_SelectedIndexChanged(null, null);
        txtCallStatus.Text = string.Empty;
        txtCallStatusId.Text = "-1";
        txtCXCRMId.Text = "0";
    }

    protected void ddlCIMainCallStatus_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddlCIMainCallStatus.Items.Count > 0 && ddlCIMainCallStatus.SelectedIndex >= 0)
        {
            LoadCallStatusList(Convert.ToInt32(ddlCIMainCallStatus.Text));
        }
    }

    protected void ddlCICallStatus_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddlCIMainCallStatus.Text == "7" && ddlCICallStatus.Text == "10")
        {
            lblCallBackDateTime.Text = Resources.CarInsurance.NewCommencementDate;

            trCallBack1.Visible = true;
            spanTimeDrowdown.Visible = false;
           
        }
        else
        {
            lblCallBackDateTime.Text = Resources.General.DateTime;
            if (!rdoCallBack.Checked)
            {
                trCallBack1.Visible = false;
                spanTimeDrowdown.Visible = true;
            }
        }
    }

    private void LoadMainCallStatusList(int intType)
    {
        try
        {
            MyDatabase _db = new MyDatabase();
            string _strSQL = "Select MainCallStatusTypeID, " + Resources.DBTable.FieldName + " AS Description from tblCXCRMMainCallStatusType Where [Status] = 1 And [Type] = " + intType.ToString();

            DataTable _dtList = new DataTable("tblList");
            _dtList = _db.GetDataTable(_strSQL);
            ddlCIMainCallStatus.Items.Clear();
            ddlCICallStatus.Items.Add(new ListItem(Resources.CarInsurance.Select, "-1"));
            if (_dtList != null && _dtList.Rows.Count > 0)
            {
                for (int i = 0; i < _dtList.Rows.Count; i++)
                {
                    ddlCIMainCallStatus.Items.Add(new ListItem(_dtList.Rows[i]["Description"].ToString(), _dtList.Rows[i]["MainCallStatusTypeID"].ToString()));
                }
            }
        }
        catch (Exception Ex)
        {
            lblCallSessionName.Text += "<br/><b style='color:red;'>" + Resources.General.ERROR + "</b>: at LoadMainCallStatusList()<br/>" + Ex.Message + "<br/><br/>" + Ex.StackTrace;
        }
    }

    private void LoadCallStatusList(int MainStatusID)
    {
        try
        {
            MyDatabase _db = new MyDatabase();
            string _strSQL = "Select CallStatusTypeID, " +
                                " '[' + CAST(StatusCode AS VARCHAR) + '] ' + " + Resources.DBTable.FieldName + " AS Description " +
                                " FROM tblCXCRMCallStatusType Where [Status] = 1 And [MainCallStatusTypeID] = " + MainStatusID.ToString();
            DataTable _dtList = new DataTable("tblList");
            _dtList = _db.GetDataTable(_strSQL);
            ddlCICallStatus.Items.Clear();
            ddlCICallStatus.Items.Add(new ListItem(Resources.CarInsurance.Select, "-1"));
            if (_dtList != null && _dtList.Rows.Count > 0)
            {
                for (int i = 0; i < _dtList.Rows.Count; i++)
                {
                    ddlCICallStatus.Items.Add(new ListItem(_dtList.Rows[i]["Description"].ToString(), _dtList.Rows[i]["CallStatusTypeID"].ToString()));
                }
            }
        }
        catch (Exception Ex)
        {
            lblCallSessionName.Text += "<br/><b style='color:red;'>" + Resources.General.ERROR + "</b>: at LoadCallStatusList()<br/>" + Ex.Message + "<br/><br/>" + Ex.StackTrace;
        }
    }

    protected void rdoCallFinish_CheckedChanged(object sender, EventArgs e)
    {
        trCallBack1.Visible = false;
        trCallBack2.Visible = false;
        if (rdoCallFinish.Checked)
        {
            LoadMainCallStatusList(1);
        }
        else if (rdoCallBack.Checked)
        {
            trCallBack1.Visible = true;
            trCallBack2.Visible = true;
            lblCallBackDateTime.Text = Resources.General.DateTime;
            LoadMainCallStatusList(2);
            spanTimeDrowdown.Visible = true;
        }
        else if (rdoFollowUp.Checked)
        {
            LoadMainCallStatusList(3);
        }

        if (ddlCIMainCallStatus.Items.Count > 0)
        {
            ddlCIMainCallStatus.SelectedIndex = 0;
            ddlCIMainCallStatus_SelectedIndexChanged(sender, e);
        }


    }

    protected void ddlAgent_SelectedIndexChanged(object sender, EventArgs e)
    {
        btnSubmit_Click(sender, e);
    }

    protected void ddlSubmittedDate_SelectedIndexChanged(object sender, EventArgs e)
    {
        btnSubmit_Click(sender, e);
    }

    protected void ddlVehicleBodyType_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddlVehicleBodyType.Text == "1")
        {
            txtCTPL.Text = "645.21";
        }
        else if (ddlVehicleBodyType.Text == "2")
        {
            txtCTPL.Text = "967.28";
        }
        else
        {
            txtCTPL.Text = "0";
        }

        txtGrossPremium_TextChanged(sender, e);
    }

    protected void ddlBrokerProvider_SelectedIndexChanged(object sender, EventArgs e)
    {
        lblPremiumError.Text = "";
        lblPremiumMessage.Text = "";
        LoadBrokerCoverType();
        lblQRefNo.Text = CE.Global.General.GetReferenceNumber(txtCarId.Text.Trim(), ddlBrokerProvider.Text.Trim());
        ddlBrokerCoverType_SelectedIndexChanged(sender, e);
    }

    protected void ddlBrokerCoverType_SelectedIndexChanged(object sender, EventArgs e)
    {
       

        if (ddlBrokerProvider.Text == "43" && (ddlBrokerCoverType.Text == "10" || ddlBrokerCoverType.Text == "11") && txtUserTypeId.Text == "1001")
        {
            ddlGarageType.Items.Clear();
            ddlGarageType.Items.Insert(0, new ListItem(Resources.CarInsurance.Garage_Authorized, "1"));
            ddlGarageType.Items.Insert(0, new ListItem(Resources.CarInsurance.Select, "-1"));
        }
        else
        {
            ddlGarageType.Items.Clear();
            ddlGarageType.Items.Insert(0, new ListItem(Resources.CarInsurance.Garage_Dealer, "2"));
            ddlGarageType.Items.Insert(0, new ListItem(Resources.CarInsurance.Garage_Authorized, "1"));
            ddlGarageType.Items.Insert(0, new ListItem(Resources.CarInsurance.Select, "-1"));
        }
        LoadDiscountPercentageList();
        LoadMonthlyInstallment();
        LoadBrokerDefault(); //Sop Create method and updated on 16 Nov 2012 from BKK

    }

    protected void grvPremiumList_SelectedIndexChanged(object sender, EventArgs e)
    {
        lblPremiumError.Text = "";
        lblPremiumMessage.Text = "";
        BrokerPremium _brokerPremium = new BrokerPremium();
        BrokerPremiumDB _brokerPremiumdb = new BrokerPremiumDB();
        ClearFields();
        if (grvPremiumList.SelectedIndex >= 0)
        {
            DataKey _dKey = grvPremiumList.SelectedDataKey;
            Int64 _premiumId = Convert.ToInt64(_dKey.Values[0]);
            Int64 _brokerId = Convert.ToInt64(_dKey.Values[1]);

            string _ProductType = "CIN";
            Int64 _CECarId = Convert.ToInt64(txtCarId.Text);
            Int64 _CustomerId = Convert.ToInt64(txtCustomerId.Text);

            _brokerPremium = _brokerPremiumdb.GetBrokerPremiumSingleItem(_premiumId, _brokerId, _CECarId, _CustomerId, _ProductType);
            if (_brokerPremium != null)
            {
                txtPremiumId.Text = _brokerPremium.CXBrokerPremiumId.ToString();
                ddlBrokerProvider.Text = _brokerPremium.CXBrokerProviderId.ToString();
                ddlBrokerProvider_SelectedIndexChanged(sender, e);
                ddlBrokerCoverType.Text = _brokerPremium.ProviderCoverTypeId.ToString();
                ddlBrokerCoverType_SelectedIndexChanged(sender, e);
                txtNetPremium.Text = _brokerPremium.Premium.ToString();

              
                if (_brokerPremium.DiscountPercentage > 5)
                {
                    ddlDiscountPercentage.Items.Clear();
                    for (int p = _brokerPremium.DiscountPercentage; p >= 0; p--)
                    {
                        ddlDiscountPercentage.Items.Add(new ListItem(p.ToString() + " " + "%", p.ToString()));
                    }
                }
                

                ddlDiscountPercentage.Text = _brokerPremium.DiscountPercentage.ToString();
                chkSelected.Checked = _brokerPremium.SelectedStatus;
              
                ddlGarageType.Text = _brokerPremium.WorkShop;
                txtDeductible.Text = _brokerPremium.DEC;
                txtFireTheft.Text = _brokerPremium.FireTheft;
                txtOwnDamage.Text = _brokerPremium.OwnDamage;
                chkCTPL.Checked = _brokerPremium.IsIncludeCMI;
                chkCTPL_CheckedChanged(sender, e);
                txtTPPD.Text = _brokerPremium.TPPD;
                txtTPBIA.Text = _brokerPremium.TPBIA;
                txtTPBIP.Text = _brokerPremium.TPBIP;
                txtBailBond.Text = _brokerPremium.BailBound;
                txtNetPremium.Text = _brokerPremium.Premium.ToString();
                txtGrossPremium.Text = _brokerPremium.TotalVMI.ToString();
                if (_brokerPremium.Info3 != string.Empty)
                {
                    ddlVehicleBodyType.Text = _brokerPremium.Info3;
                    ddlVehicleBodyType_SelectedIndexChanged(sender, e);
                    txtCTPL.Text = _brokerPremium.TotalCMI.ToString();
                }

                if (_brokerPremium.Info4 == "1")
                {
                    chkCompanyStaff.Checked = true;
                }
                else
                {
                    chkCompanyStaff.Checked = false;
                }

                txtFloodCoverAmount.Text = _brokerPremium.Info5;

                if (_brokerPremium.Info6 == "1")
                {
                    chkNamedDriver.Checked = true;
                }
                else
                {
                    chkNamedDriver.Checked = false;
                }

                txtAccModCost.Text = _brokerPremium.Info7;

                ddlDiscountPercentage.Text = _brokerPremium.DiscountPercentage.ToString();
                ddlDiscountPercentage_SelectedIndexChanged(sender, e);
                txtFinalAnnualPremium.Text = _brokerPremium.FinalAnnualPremium.ToString("#0.00");
                txtFinalAnnualPremiumNoDisc.Text = _brokerPremium.FinalAnnualPremiumNoDisc.ToString("#0.00");
                txtPA.Text = _brokerPremium.PADriver.ToString();
                txtMED.Text = _brokerPremium.MedicalExpense.ToString();
                txtEditLicensePlate.Text = _brokerPremium.Info2;
                lblEditLicensePlate.Text = _brokerPremium.Info2;
                txtPremiumChangeComments.Text = _brokerPremium.Info8;
               

                if (_brokerPremium.Bank != string.Empty && _brokerPremium.Bank != "-1")
                {
                    ddlCreditCard.Text = _brokerPremium.Bank;
                }
              

                if (_brokerPremium.NoofInstallment > 2)
                {
                    
                    ddlNoofInstallments.Items.Clear();
                    ddlNoofInstallments.Items.Add(new ListItem("3" + " " + Resources.CarInsurance.Installment, "3"));
                    ddlNoofInstallments.Items.Add(new ListItem("4" + " " + Resources.CarInsurance.Installment, "4"));
                    ddlNoofInstallments.Items.Add(new ListItem("6" + " " + Resources.CarInsurance.Installment, "6"));
                    ddlNoofInstallments.Items.Add(new ListItem("0" + " " + Resources.CarInsurance.Installment, "0"));
                   
                    ddlNoofInstallments.Text = _brokerPremium.NoofInstallment.ToString();
                }
                ddlCreditCard_SelectedIndexChanged(null, null);
                NoofInstallments_SelectedIndexChanged(null, null);
                if (_brokerPremium.PaymentOption != string.Empty && _brokerPremium.PaymentOption != "-1")
                {
                    ddlPaymentOption.Text = _brokerPremium.PaymentOption;
                }
              
            }
            else
            {
                ClearFields();
            }
        }
        else
        {
            ClearFields();
        }
        _brokerPremium = null;
        _brokerPremiumdb = null;
    }

    private void ClearFields()
    {
        txtPremiumId.Text = "0";
        txtNetPremium.Text = "";
        ddlDiscountPercentage.Text = "0";
      
        ddlGarageType.Text = "-1";
        chkSelected.Checked = false;

        txtDeductible.Text = "";
       

        txtFireTheft.Text = "";
       
        chkCTPL.Checked = true;
        txtCTPL.Enabled = true;
        chkChangePremium.Checked = false;

        txtTPPD.Text = "";
        txtTPBIA.Text = "";
        txtTPBIP.Text = "";
        txtPA.Text = "";
        txtMED.Text = "";
        txtBailBond.Text = "";

        lblTax.Text = "0";
        lblVAT.Text = "0";
        lblDiscountAmount.Text = "0";
        lblAnnualPremium.Text = "0";
        lblNetPremium.Text = "0";
        txtGrossPremium.Text = "0";
        txtFinalAnnualPremium.Text = "0";
        txtFinalAnnualPremiumNoDisc.Text = "0";
        txtFinalAnnualPremium.ReadOnly = true;
        txtFinalAnnualPremiumNoDisc.ReadOnly = true;

        txtFloodCoverAmount.Text = "0";
        txtAccModCost.Text = "0";
        txtPremiumChangeComments.Text = string.Empty;

        
        lblTotalGrossPremiumWD.Text = "0";
        lblFirstInstallmentWD.Text = "0";
        lblLastInstallmentWD.Text = "0";
        lblTotalGrossPremiumWOD.Text = "0";
        lblFirstInstallmentWOD.Text = "0";
        lblLastInstallmentWOD.Text = "0";
        lblFirstInstallmentWDdesc.Text = string.Empty;
        lblFirstInstallmentWODdesc.Text = string.Empty;

        ddlNoofInstallments.Items.Clear();
        ddlNoofInstallments.Items.Add(new ListItem("0" + " " + Resources.CarInsurance.Installment, "0"));

        ddlCreditCard.Items.Clear();
        ddlCreditCard.Items.Add(new ListItem(Resources.CarInsurance.Select, "-1"));

        ddlGGDiscount.Items.Clear();
        ddlGGDiscount.Items.Add(new ListItem("0 %", "0"));

       
    }

    private void LoadBrokerProvider()
    {
        lblPremiumError.Text = "";
        lblPremiumMessage.Text = "";
        DataTable _dtBrokerProvider = General.GetComboItem("BrokerProvider", true);
        if (_dtBrokerProvider != null && _dtBrokerProvider.Rows.Count > 0)
        {
            ddlBrokerProvider.DataSource = _dtBrokerProvider;
            ddlBrokerProvider.DataTextField = _dtBrokerProvider.Columns[0].ColumnName.ToString();
            ddlBrokerProvider.DataValueField = _dtBrokerProvider.Columns[1].ColumnName.ToString();
            ddlBrokerProvider.DataBind();
        }

        ddlBrokerProvider.Items.Insert(0, new ListItem("Select", "-1"));
      
    }

    private void LoadBrokerCoverType()
    {
        lblPremiumError.Text = "";
        lblPremiumMessage.Text = "";
        ddlBrokerCoverType.Items.Clear();
        
        MyDatabase _db = new MyDatabase();
        DataTable _dtBrokerCoverType = new DataTable("tblBrokerCoverType");
        _dtBrokerCoverType = _db.GetDataTable("Select ProviderCoverTypeID, " + Resources.DBTable.FieldName + " FROM tblCXBrokerProviderCoverType WHERE Status = 1 ORDER BY ProviderCoverTypeID");
        if (ddlBrokerProvider.Text == "41" && txtUserTypeId.Text == "1001")
        {
            _dtBrokerCoverType = _db.GetDataTable("Select ProviderCoverTypeID, " + Resources.DBTable.FieldName + " FROM tblCXBrokerProviderCoverType WHERE Status = 1 AND ProviderCoverTypeID<> 11 ORDER BY ProviderCoverTypeID");
        }
        if (_dtBrokerCoverType != null && _dtBrokerCoverType.Rows.Count > 0)
        {
            ddlBrokerCoverType.DataSource = _dtBrokerCoverType;
            ddlBrokerCoverType.DataTextField = _dtBrokerCoverType.Columns[1].ColumnName.ToString();
            ddlBrokerCoverType.DataValueField = _dtBrokerCoverType.Columns[0].ColumnName.ToString();
            ddlBrokerCoverType.DataBind();
        }
       

        ddlBrokerCoverType.Items.Insert(0, new ListItem(Resources.CarInsurance.Select, "-1"));

       
    }

    private void LoadAgentList()
    {
        lblPremiumError.Text = "";
        lblPremiumMessage.Text = "";
        try
        {
            MyDatabase _db = new MyDatabase();
            DataTable _dt = new DataTable("tblList");
            string _spName = "sprocCXCRMGetAgentList";

            _dt = _db.GetDataTable(_spName);
            ddlCBAgentList.Items.Clear();
            if (_dt != null && _dt.Rows.Count > 0)
            {
                ddlCBAgentList.DataSource = _dt;
                ddlCBAgentList.DataTextField = "FULLNAME";
                ddlCBAgentList.DataValueField = "CEID";
                ddlCBAgentList.DataBind();
            }
        }
        catch (Exception Ex)
        {
        }

        txtPremiumId.Text = "0";
        txtNetPremium.Text = "";
        ddlDiscountPercentage.Text = "0";
       
        ddlGarageType.Text = "-1";
        chkSelected.Checked = false;
    }

    public string GetAgentCallStatus(string CECarId)
    {
        string _Status = "None";
        MyDatabase _db = new MyDatabase();
        string strSql = "SELECT CallStatus FROM tblCXCINoMatchCallStatus WHERE CECarId = " + CECarId;
        string _AgentCallStatusId = "-1";
        object _result = _db.ExecuteScalarSqlStatement(strSql);
        if (_result != null)
        {
            _AgentCallStatusId = _result.ToString();
        }
        if (_AgentCallStatusId == "0")
        {
            _Status = "Negative";
        }
        else if (_AgentCallStatusId == "1")
        {
            _Status = "Positive";
        }
        else if (_AgentCallStatusId == "2")
        {
            _Status = "Follow-up";
        }
        return _Status;
    }

    public string GetCallBackCount()
    {
        MyDatabase _db = new MyDatabase();
        string _spName = "sprocCXCRMGetCallBackCount";

        SortedList _paraList = new SortedList();
        _paraList.Add("@CustomerID", txtCustomerId.Text);
        _paraList.Add("@CallTypeID", lblCallType.Text);
        _paraList.Add("@AgentID", txtAgentId.Text);
        string _callBackCount = "0";
        object _result = _db.ExecuteScalarSP(_spName, _paraList);
        if (_result != null)
        {
            _callBackCount = _result.ToString();
        }

        return _callBackCount;
    }


    private NonGGPremiumListPDFOutput CreateNonGGPDFObject()
    {
        Int64 CECarId = Convert.ToInt64(txtCarId.Text);
       

     
        NonGGPremiumListPDFOutput _nonGGPdf = new NonGGPremiumListPDFOutput();
       
        _nonGGPdf.Title = "ใบเสนอราคาเบี้ยประกันรถยนต์";
        _nonGGPdf.Footer = "";//"For more information, please login to www.GluayGluay.com.";

        _nonGGPdf.CarId = txtCarId.Text;
        _nonGGPdf.CustomerName = lblName.Text + " " + lblLastName.Text;
        _nonGGPdf.CarPlateNumber = txtEditLicensePlate.Text;
        _nonGGPdf.Email = lblEmailAddress.Text;
        _nonGGPdf.DOB = lblDOB.Text;
        _nonGGPdf.Mobile = lblMobileNo.Text;
        _nonGGPdf.Gender = lblGender.Text;
        _nonGGPdf.Occupation = lblOccupation.Text;

        _nonGGPdf.CurrentInsurer = lblCurrentInsurer.Text;
        _nonGGPdf.CarMakeModel = lblCarMakeModel.Text;
        _nonGGPdf.CarModelYear = lblRegYear.Text;
        _nonGGPdf.AnyClaim = lblClaimInfo.Text;
        _nonGGPdf.CommnecementDate = ddlEditCoverCommencementDate.Text;
        lblEditCoverCommencementDate.Text = ddlEditCoverCommencementDate.Text;
       
        _nonGGPdf.InsuranceType = lblInsuranceType.Text;
        _nonGGPdf.GarageType = lblGarageType.Text;
        _nonGGPdf.QuoteDateTime = lblRefModifiedDateTime.Text;
        _nonGGPdf.VehicleTypeUsage = lblVehicleType.Text;
        _nonGGPdf.IncludeCTPL = lblCTPL.Text;
        _nonGGPdf.NCB = ddlEditNCB.Text;
        _nonGGPdf.AgentName = Session[General.UserName].ToString();
        _nonGGPdf.AgentEmail = Session[General.SMTPReplyTo].ToString();
        _nonGGPdf.AgentContactNo = Session[General.UserPhoneNo].ToString();
        if (ddlEditNamedDriver.Text != "0")
        {
            _nonGGPdf.NamedDriver = ddlEditNamedDriver.Text;
        }
        else
        {
           
            _nonGGPdf.NamedDriver = Resources.Proposal.No;
        }

        MyDatabase _db = new MyDatabase();
        SortedList _paraList = new SortedList();
        _paraList.Add("@CECarID", txtCarId.Text);
        _paraList.Add("@ProductType", "CIN");
        _paraList.Add("@RefCEUserId", "0");
        _paraList.Add("@LangOption", "1");

        DataTable _dtPremiumList = new DataTable("tblPremiumList");
        _dtPremiumList = _db.GetDataTableBySP("sprocCXBrokerPremiumSelectItemList", _paraList);
        if (_dtPremiumList != null)
        {
            _nonGGPdf.ResultGridTable = _dtPremiumList;
        }
        return _nonGGPdf;
    }

    protected void btnPremiumDownload_Click(object sender, EventArgs e)
    {
        if (grvPremiumList.Rows.Count > 0)
        {
            NonGGPremiumListPDFOutput _nonGGPdf = CreateNonGGPDFObject();

            string _fileName = _nonGGPdf.GeneratePDF(HttpContext.Current.Session["Language"].ToString());
            FileInfo file = new System.IO.FileInfo(_fileName);
            if (!file.Exists)
            {
                Response.StatusCode = 500;
                Response.End();
                return;
            }
            Response.Clear();
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.Cache.SetNoStore();
            Response.Cache.SetExpires(DateTime.MinValue);
            Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
            Response.AddHeader("Content-Length", file.Length.ToString());
            Response.ContentType = "application/octet-stream";
            Response.WriteFile(file.FullName);
            ApplicationInstance.CompleteRequest();
            Response.End();
        }
        else
        {
            ClientScript.RegisterStartupScript(btnPremiumDownload.GetType(), "DownloadPremiumAlert", "alert('No item to download!');", true);
        }
    }

    public string GetDownloadURl(Int64 CECarId, string VehicleNo)
    {
        string _url = "";
        string inputval = CECarId.ToString() + "@" + VehicleNo;
        _url = "javascript:OpenPremiumDownload('" + inputval + "');";
        return _url;
    }

    public void SetPremiumDownLoadLink()
    {
        string url = "PremiumDownload.aspx?carid=" + txtCarId.ToString();
        StringBuilder sb = new StringBuilder();
        sb.Append("<script>");
        sb.Append("window.open('" + url + "', '', '');");
        sb.Append("</scri");
        sb.Append("pt>");
        ClientScript.RegisterStartupScript(GetType(), "test", sb.ToString());

    }

    public void GeneratePremium(Int64 CECarId)
    {

        Int32 _Count = 0;
        Label lblContent = new Label();
        string _html = "";
        string _fileName = "FileName";
        _fileName = "Premium_" + CECarId;
        string _UserCover = "";

        string _ProductType = "CIN";
        DataSet _dsPremium = new DataSet();
        BrokerPremiumDB _prokerpremiumdb = new BrokerPremiumDB();
        _dsPremium = _prokerpremiumdb.GetBrokerPremium(CECarId, _ProductType, Convert.ToInt16(lblLangOption.Text));
        if (_dsPremium.Tables[0].Rows.Count > 0)
        {
            if (_dsPremium.Tables.Count > 1)
            {
                if (_dsPremium.Tables[1].Rows.Count > 0)
                {
                    _UserCover = _dsPremium.Tables[1].Rows[0]["ProviderCoverTypeDesc"].ToString();
                }
            }

            _Count = _dsPremium.Tables[0].Rows.Count;
            if (_Count > 4)
            {
                _Count = 4;
            }

            #region variables
            string[] _Insurer = new string[_Count];
            string[] _Workshop = new string[_Count];
            string[] _Premium = new string[_Count];
            string[] _Excess = new string[_Count];
            string[] _QuoteId = new string[_Count];
            string[] _Cover = new string[_Count];
            string[] _Package = new string[_Count];
            #endregion

            for (int i = 0; i < _Count; i++)
            {
                #region Values assign to variables
                _Insurer[i] = _dsPremium.Tables[0].Rows[i]["CompanyName"].ToString();
                _Workshop[i] = _dsPremium.Tables[0].Rows[i]["WorkShop"].ToString();
                _Premium[i] = "$" + _dsPremium.Tables[0].Rows[i]["Premium"].ToString();
                _Excess[i] = "$" + _dsPremium.Tables[0].Rows[i]["Excess"].ToString();
                _QuoteId[i] = CECarId.ToString();
                _Cover[i] = _dsPremium.Tables[0].Rows[i]["ProviderCoverTypeDesc"].ToString();
                _Package[i] = _dsPremium.Tables[0].Rows[i]["Package"].ToString();
                #endregion
            }

            #region Html

            Uri myUri = new Uri(HttpContext.Current.Request.Url.ToString());
            string domainUrl = "";
            string _strCXLive = CE.Configuration.MyConfigurationManager.GetAppSettingValue("CXCINMIsCXLive");
            if (_strCXLive == "2")
            {
                domainUrl = "http://" + myUri.Authority;
            }
            else
            {
                domainUrl = "http://" + myUri.Host;
            }
            string imgUrl = domainUrl + "/CX_Broker/images/header/kim_banner.png";

            _html = "<table style='width: 100%; background-color: white;' cellpadding='0' cellspacing='0'>"

                    + "<tr>"
                    + "<td align='left' style='width:100%'><img src='" + imgUrl + "' alt='KIM Brokers' /></td>"
                    + "</tr>"

                    + "<tr>"
                    + "<td align='left' style='width:100%'>&nbsp;</td>"
                    + "</tr>"

                    + "<tr>"
                    + "<td align='left' style='width:100%'>Below are the instant competitive quotations sourced from some insurers.</td>"
                    + "</tr>"

                    + "<tr>"
                    + "<td align='left' style='width:100%'>&nbsp;</td>"
                    + "</tr>"

                    + "<tr>"
               
                    + "<td align='left' style='width:100%'>Vehicle Number: " + "N/A" + "</td>"
                    + "</tr>"

                    + "<tr>"
                    + "<td align='left' style='width:100%'>Type of Cover: " + _UserCover.ToString() + "</td>"
                    + "</tr>"

                    + "<tr>"
                    + "<td align='left' style='width:100%'>&nbsp;</td>"
                    + "</tr>"

                    + "<tr>"
                    + "<td align='left' style='width:100%'><b>QUOTES</b></td>"
                    + "</tr>"

                    + "<tr>"
                    + "<td align='left' style='width:100%'>"
                    + "<table style='width: 100%; background-color: white;' cellpadding='5' cellspacing='2' border='1'>"
                    + "<tr>"
                    + "<td align='left' style='width:150px'>&nbsp;</td>";
            for (int j = 1; j <= _Count; j++)
            {
                _html += "<td align='center' style='width:250px'>Quotation " + j + "</td>";
            }
            _html += "</tr>"

            + "<tr>"
            + "<td align='left' style='width:150px'>Quote ID</td>";
            for (int j = 1; j <= _Count; j++)
            {
                _html += "<td align='center' style='width:250px'> " + _QuoteId[j - 1].ToString() + "</td>";
            }
            _html += "</tr>"

            + "<tr>"
            + "<td align='left' style='width:150px'>Insurer</td>";
            for (int j = 1; j <= _Count; j++)
            {
                _html += "<td align='center' style='width:250px'> " + _Insurer[j - 1].ToString() + "</td>";
            }
            _html += "</tr>"

            + "<tr>"
            + "<td align='left' style='width:150px'>Restriction on Workshop</td>";
            for (int j = 1; j <= _Count; j++)
            {
                _html += "<td align='center' style='width:250px'> " + _Workshop[j - 1].ToString() + "</td>";
            }
            _html += "</tr>"

            + "<tr>"
            + "<td align='left' style='width:150px'>Cover Type</td>";
            for (int j = 1; j <= _Count; j++)
            {
                _html += "<td align='center' style='width:250px'> " + _Cover[j - 1].ToString() + "</td>";
            }
            _html += "</tr>"

            + "<tr>"
            + "<td align='left' style='width:150px'>Package</td>";
            for (int j = 1; j <= _Count; j++)
            {
                _html += "<td align='center' style='width:250px'> " + _Package[j - 1].ToString() + "</td>";
            }
            _html += "</tr>"

            + "<tr>"
            + "<td align='left' style='width:150px'>Premium</td>";
            for (int j = 1; j <= _Count; j++)
            {
                _html += "<td align='center' style='width:250px; color:blue; font-weight:bold;'> " + _Premium[j - 1].ToString() + "</td>";
            }
            _html += "</tr>"

            + "<tr>"
            + "<td align='left' style='width:150px'>Excess (Insured + Named Drivers)</td>";
            for (int j = 1; j <= _Count; j++)
            {
                _html += "<td align='center' style='width:250px; color:blue; font-weight:bold;'> " + _Excess[j - 1].ToString() + "</td>";
            }
            _html += "</tr>"
            + "</table>"
            + "</td>"
            + "</tr>"

            + "<tr>"
            + "<td align='left' style='width:100%'>&nbsp;</td>"
            + "</tr>"

            + "<tr>"
            + "<td align='left' style='width:100%'>&bull; This Quote Is Subject To the Insurer's Final Confirmation And Coverage Is Only Effective When The Insurer Has Accepted The Risk</td>"
            + "</tr>"

            + "<tr>"
            + "<td align='left' style='width:100%'>&bull; The Insurer Reserves The Right To Revise or Withdraw The Quote If Any Of the Information Given Differs From The Actual Risk</td>"
            + "</tr>"

            + "<tr>"
            + "<td align='left' style='width:100%'>&bull; Unless Otherwise Specified, The Quote Is Valid Only For 14 Days From The Date Of Quote</td>"
            + "</tr>"

            + "<tr>"
            + "<td align='left' style='width:100%'>&bull; All premiums quoted are nett, ie where applicable, inclusive of NCD, Safe Driver Discount and prevailing GST</td>"
            + "</tr>"

            + "</table>";
            #endregion

            string _HeaderText = "";

            Label lblPremiumHtml = new Label();
            lblPremiumHtml.Text = _html;
            ExportHtml(_fileName, lblPremiumHtml, _HeaderText);
        }
    }

    protected void btnReset_Click(object sender, EventArgs e)
    {
        Response.Redirect(lblResetUrl.Text.ToString());
    }

   

    public void ExportHtml(string fileName, Label lblPremiumHtml, string headerText)
    {
        string attachment = "attachment; filename=" + fileName + ".htm";
        Response.ClearContent();
        Response.AddHeader("content-disposition", attachment);
        Response.ContentType = "text/HTML";
        StringWriter sw = new StringWriter();
        HtmlTextWriter htw = new HtmlTextWriter(sw);
        HtmlForm frm = new HtmlForm();
        frm.InnerHtml = headerText;
        lblPremiumHtml.Parent.Controls.Add(frm);
        frm.Attributes["runat"] = "server";
        frm.Controls.Add(lblPremiumHtml);
        frm.RenderControl(htw);
        Response.Write(sw.ToString());
        Response.End();

        
    }

    protected void gvCallHistory_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {

           
            Int64 value = Convert.ToInt64(e.Row.Cells[2].Text);
          
            if (value.ToString() == txtCarId.Text)
            {
                e.Row.Cells[2].BackColor = System.Drawing.Color.FromName("#c6c6c6");
                e.Row.Cells[2].Font.Bold = true;
                e.Row.Cells[2].Font.Size = FontUnit.Medium;

                e.Row.Cells[4].BackColor = System.Drawing.Color.FromName("#c6c6c6");
                e.Row.Cells[4].Font.Bold = true;
                
                e.Row.BackColor = System.Drawing.Color.FromName("#ffffcc");
                e.Row.Height = Unit.Pixel(Convert.ToInt32(e.Row.Height.Value + 60d));

                lblCallHistoryFoundCount.Text = (Convert.ToInt32(lblCallHistoryFoundCount.Text) + 1).ToString();
                lblCallHistoryMessage.Text = "(" + lblCallHistoryFoundCount.Text + ") " + Resources.General.Callhistoryfound + "";
                lblCallHistoryFoundCount.Visible = false;
                
            }
            else
            {
                if (lblCallHistoryFoundCount.Text == "0")
                {
                    lblCallHistoryMessage.Text = Resources.General.Nocallhistoryfor + " " + Resources.CarInsurance.CarId + ": " + txtCarId.Text;
                }
            }
            
        }
        else if (lblCallHistoryFoundCount.Text == "0")
        {
            lblCallHistoryMessage.Text = Resources.General.Nocallhistoryfor + " " + Resources.CarInsurance.CarId + ": " + txtCarId.Text;
            lblCallHistoryFoundCount.Visible = false;
        }
    }

    protected void csvTargetDate_ServerValidate(object source, ServerValidateEventArgs args)
    {
        if (rdoCallBack.Checked || trCallBack1.Visible == true)
        {
            string _strTargetDateTime = ddlTDay.Text + "/" + ddlTMonth.SelectedItem.Text + "/" + ddlTYear.Text + " " + ddlTHour.Text + ":" + ddlTMin.Text;

            DateTime _dtTargetDateTime = dateTimeNow;

            DateTime _dtLimitDateTime = dateTimeNow.AddDays(21);

            if (ddlCIMainCallStatus.Text == "7" && ddlCICallStatus.Text == "10")
            {
                _dtLimitDateTime = dateTimeNow.AddDays(60);
                _strTargetDateTime = ddlTDay.Text + "/" + ddlTMonth.SelectedItem.Text + "/" + ddlTYear.Text;
            }

            if (DateTime.TryParse(_strTargetDateTime, out _dtTargetDateTime))
            {
                if (DateTime.Compare(dateTimeNow, _dtTargetDateTime) <= 0)
                {
                    txtCallBackDateTime.Text = _dtTargetDateTime.ToString("dd/MMM/yyyy hh:mm:ss tt");

                    if (ddlCIMainCallStatus.Text == "7" && ddlCICallStatus.Text == "10")
                    {
                        if (DateTime.Compare(_dtTargetDateTime, _dtLimitDateTime) > 0)
                        {
                            args.IsValid = true;
                        }
                        else
                        {
                            args.IsValid = false;
                            csvTargetDate.ErrorMessage = Resources.General.CommencementCheck;
                            lblCallStatusMessage.Text = Resources.General.CommencementCheck;
                        }
                    }
                    else
                    {
                        if (DateTime.Compare(_dtTargetDateTime, _dtLimitDateTime) <= 0)
                        {
                            args.IsValid = true;
                        }
                        else
                        {
                            args.IsValid = false;
                            csvTargetDate.ErrorMessage = Resources.General.CallBackDateTimeInvalid + " " + Resources.General.CallBackDaysLimitMessage;
                            lblCallStatusMessage.Text = Resources.General.CallBackDateTimeInvalid + " " + Resources.General.CallBackDaysLimitMessage;
                        }
                    }
                }
                else
                {
                    args.IsValid = false;
                    if (ddlCIMainCallStatus.Text == "7" && ddlCICallStatus.Text == "10")
                    {
                        csvTargetDate.ErrorMessage = Resources.General.CommencementCheck;
                        lblCallStatusMessage.Text = Resources.General.CommencementCheck;
                    }
                    else
                    {
                        csvTargetDate.ErrorMessage = Resources.General.CallBackDateTimeOlder;
                        lblCallStatusMessage.Text = Resources.General.CallBackDateTimeOlder;
                    }
                }
            }
            else
            {
                args.IsValid = false;
                txtCallBackDateTime.Text = "0";
                if (ddlCIMainCallStatus.Text == "7" && ddlCICallStatus.Text == "10")
                {
                    csvTargetDate.ErrorMessage = Resources.General.CommencementCheck;
                    lblCallStatusMessage.Text = Resources.General.CommencementCheck;
                }
                else
                {
                    csvTargetDate.ErrorMessage = Resources.General.CallBackDateTimeInvalid;
                    lblCallStatusMessage.Text = Resources.General.CallBackDateTimeInvalid;
                }
            }
        }
    }

    protected void btnNext_Click(object sender, EventArgs e)
    {
        Response.Redirect("~/SiteUserHome.aspx");
        
    }

    protected void grvPremiumList_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName.Equals("MyDelete"))
        {
            if (e.CommandArgument != null)
            {
                if (lblCarMoreDetailID.Text == "-1")
                {
                    Int64 _AgentId = 0;
                    Int64 _CXBrokerPremiumId = 0;
                    _CXBrokerPremiumId = Convert.ToInt64(e.CommandArgument);
                    _AgentId = Convert.ToInt64(Session[CE.Global.General.UserId].ToString());

                    MyDatabase _db = new MyDatabase();
                    SortedList _paraList = new SortedList();
                    _paraList.Add("@CXBrokerPremiumId", _CXBrokerPremiumId);
                    _paraList.Add("@AgentId", _AgentId);
                    int _effCount = _db.ExecuteNonSqlSP("sprocCXBrokerPremiumDeleteSingleItem", _paraList);
                    if (_effCount > 0)
                    {
                        ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('Delete was successful.');", true);
                    }
                    
                    grvPremiumList.DataBind();


                    if (grvPremiumList.Rows.Count > 0)
                    {
                        lblAppStatusMessage.Text = "( " + grvPremiumList.Rows.Count.ToString() + " ) record(s) found.";
                        chkConfirmEmail.Checked = false;
                        chkConfirmEmail_CheckedChanged(null, null);
                    }
                    else
                    {
                        lblAppStatusMessage.Text = "No records found.";
                    }

                    lblPremiumError.Text = "";
                    lblPremiumMessage.Text = "";
                    txtPremiumId.Text = "0";
                    txtNetPremium.Text = "";
                    ddlDiscountPercentage.Text = "0";
                   
                    ddlGarageType.Text = "-1";
                    chkSelected.Checked = false;
                    ddlBrokerProvider.SelectedIndex = 0;
                    ddlBrokerCoverType.SelectedIndex = 0;
                    ddlBrokerProvider_SelectedIndexChanged(null, null);
                    uplPremiumList.Update();
                }
                else
                {
                    ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('Delete failed. Found application details.');", true);
                }
            }
        }
    }

    protected void btnEditSubmit_Click(object sender, EventArgs e)
    {
        if (Convert.ToInt32(lblCarMoreDetailID.Text) > 0)
        {
            btnSubmitPremium.Enabled = false;
            btnNewPremium.Enabled = false;
            btnEditSubmit.Enabled = false;
            lblPremiumMessage.Text = Resources.General.NonGGFoundAppDetailSubmission;
            lblPremiumMessage.ForeColor = System.Drawing.Color.Red;
            ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('" + Resources.General.NonGGFoundAppDetailSubmission + "');", true);
            return;
        }

        Page.Validate("editdetail");
        if (Page.IsValid)
        {
            MyDatabase _myDB = new MyDatabase();

            string _strUpdateSQL = "UPDATE tblCarDetailTH SET ";

            _strUpdateSQL += " Info15 = '" + txtEditLicensePlate.Text + "', ";
            _strUpdateSQL += " Info16 = '" + ddlEditNCB.Text + "', ";
            _strUpdateSQL += " Info17 = '" + ddlEditNamedDriver.Text + "', ";
            //_strUpdateSQL += " Info18 = '" + txtEditSumInsuredAmount.Text + "', ";
            _strUpdateSQL += " Info19 = '" + ddlEditCoverCommencementDate.Text + "' ";
            _strUpdateSQL += " WHERE CarID = " + txtCarId.Text + " AND RefCEUserID = " + txtCustomerId.Text;

            int _retValue = _myDB.ExecuteNonSqlStatement(_strUpdateSQL);
            if (_retValue > 0)
            {
                lblEditDetailMessage.Text = "Updating succeeded";
                lblEditLicensePlate.Text = txtEditLicensePlate.Text;
                lblEditCoverCommencementDate.Text = ddlEditCoverCommencementDate.Text;
                lblEditCoverCommencementDateMessage.Text = string.Empty;
                //ddlBrokerProvider_SelectedIndexChanged(sender, e);
                LoadDiscountPercentageList();
            }
            else
            {
                lblEditDetailMessage.Text = "Updating failed";
            }

        }
    }

    protected void btnGoBack_Click(object sender, EventArgs e)
    {
        //Response.Redirect("~/carinsurance/ViewCICustomerCallNew.aspx?leadid=" + lblAgentLeadID.Text + "&calltype=" + lblCallType.Text);
    }

    private void CheckQuoteStatus()
    {
        lblCommenceDateStatusMessage.Visible = false;
        lblQuoteDateTimeStatusMessage.Visible = false;

        if (lblCommenceDateStatus.Text == "0" && lblQuoteDateTimeStatus.Text == "1")
        {
            lblQuoteStatusMessage.Text = lblCommenceDateStatusMessage.Text;
            lblQuoteStatusMessage.Font.Bold = true;
            lblQuoteStatusMessage.ForeColor = System.Drawing.Color.Red;
        }
        else if (lblQuoteDateTimeStatus.Text == "0" && lblCommenceDateStatus.Text == "1")
        {
            lblQuoteStatusMessage.Text = lblQuoteDateTimeStatusMessage.Text;
            lblQuoteStatusMessage.Font.Bold = true;
            lblQuoteStatusMessage.ForeColor = System.Drawing.Color.Red;
        }
        else if (lblQuoteDateTimeStatus.Text == "0" && lblCommenceDateStatus.Text == "0")
        {
            lblQuoteDateTimeStatusMessage.Visible = false;
            lblCommenceDateStatusMessage.Visible = false;
            lblQuoteStatusMessage.Text = Resources.General.CommencementOVER;
            lblQuoteStatusMessage.Font.Bold = true;
            lblQuoteStatusMessage.ForeColor = System.Drawing.Color.Red;
        }
        else
        {
            lblQuoteDateTimeStatusMessage.Visible = false;
            lblCommenceDateStatusMessage.Visible = false;
            lblQuoteStatusMessage.Text = Resources.General.EverythingOK;
            lblQuoteStatusMessage.Font.Bold = true;
            lblQuoteStatusMessage.ForeColor = System.Drawing.Color.Green;
        }

        divBuyNowStatusMessage.Visible = true;
       
    }

    private void CheckApplicationStatus()
    {
        MyDatabase _db = new MyDatabase();
        SortedList _paraList = new SortedList();
        _paraList.Add("@CECarID", txtCarId.Text);
        _paraList.Add("@CustomerID", txtCustomerId.Text);
        DataTable _dtApp = new DataTable("tblApp");
        _dtApp = _db.GetDataTableBySP("sprocCXCRMNonGGApplicationStatusSelectItem", _paraList);

        if (_dtApp != null && _dtApp.Rows.Count > 0)
        {
            lblCarMoreDetailID.Text = _dtApp.Rows[0]["CECarMoreDetailId"].ToString();
            lblAppStatus.Text = string.Empty;
            

            lblAppStatusMessage.Text = string.Empty;
            lblAppStatusMessage.Text = Resources.General.NonGGFoundAppDetailSubmission;
            lblAppStatusMessage.ForeColor = System.Drawing.Color.Red;
            lblAppStatusMessage.Font.Bold = true;

            ddlBrokerProvider.Text = _dtApp.Rows[0]["ProviderCompanyId"].ToString();
            ddlBrokerProvider_SelectedIndexChanged(null, null);
            ddlBrokerCoverType.Text = _dtApp.Rows[0]["InsuranceType"].ToString();
            ddlBrokerCoverType_SelectedIndexChanged(null, null);

            ddlBrokerCoverType.Enabled = false;
            ddlBrokerProvider.Enabled = false;
            chkCTPL.Enabled = false;
            txtCTPL.Enabled = false;
            txtGrossPremium.Enabled = false;
            txtFinalAnnualPremium.Enabled = false;
           

            txtEditLicensePlate.Enabled = false;
            ddlEditNCB.Enabled = false;
            
            ddlEditNamedDriver.Enabled = false;

            ddlGarageType.Enabled = false;
            chkSelected.Enabled = false;
            SetGVPremiumSelectedIndex();

            lblCarMoreDetailID.Visible = false;
            lblAppStatus.Visible = false;
            btnSubmitPremium.Enabled = false;
            btnEditSubmit.Enabled = false;
            chkConfirmEmail.Visible = false;
        }
        else
        {
            SetGVPremiumSelectedIndex();
            ddlBrokerCoverType.Enabled = true;
            ddlBrokerProvider.Enabled = true;
            chkCTPL.Enabled = true;
            txtCTPL.Enabled = true;
            txtGrossPremium.Enabled = true;
            txtFinalAnnualPremium.Enabled = true;
            ddlDiscountPercentage.Enabled = true;

            txtEditLicensePlate.Enabled = true;
            ddlEditNCB.Enabled = true;
            ddlEditNamedDriver.Enabled = true;

            ddlGarageType.Enabled = true;
            chkSelected.Enabled = true;
            lblCarMoreDetailID.Text = "-1";
            lblAppStatus.Text = string.Empty;
            btnSubmitPremium.Enabled = true;
            btnEditSubmit.Enabled = true;
            lblAppStatusMessage.Text = string.Empty;
            if (grvPremiumList.Rows.Count > 0)
            {
                lblAppStatusMessage.Text = "( " + grvPremiumList.Rows.Count.ToString() + " ) record(s) found.";
                chkConfirmEmail.Checked = false;
                chkConfirmEmail_CheckedChanged(null, null);
            }
            else
            {
                lblAppStatusMessage.Text = "No records found.";
            }

            lblAppStatusMessage.ForeColor = System.Drawing.Color.Red;
            lblAppStatusMessage.Font.Bold = true;

        }
    }

    private void SetGVPremiumSelectedIndex()
    {
        foreach (GridViewRow myRow in grvPremiumList.Rows)
        {
            string _selectStatus = myRow.Cells[13].Text.ToString().ToLower();
          
            if (_selectStatus == "yes")
            {
                grvPremiumList.SelectedIndex = myRow.RowIndex;
                myRow.Cells[10].ForeColor = System.Drawing.Color.Red;
                lblSelectedRefNo.Text = myRow.Cells[5].Text.ToString();
               
                break;
            }
        }
    }

    protected void btnGoToNonGGPendingApp_Click(object sender, EventArgs e)
    {
        if (lblSelectedRefNo.Text != string.Empty)
        {
            if (lblRenewalStaus.Text == "0")
            {
                Response.Redirect("~/carinsurance/offline/NonGGPackageApplication.aspx?refno=" + lblQRefNo.Text);
            }
            else
            {
                if (lblLastYearRefNo.Text != string.Empty)
                {
                    Response.Redirect("~/carinsurance/offline/NonGGPackageApplication.aspx?refno=" + lblQRefNo.Text + "&lyrrefno=" + lblLastYearRefNo.Text);
                }
            }
        }
        else
        {
            lblPremiumMessage.Text = "Please select a quotation for customer.";
            lblPremiumMessage.ForeColor = System.Drawing.Color.Red;
        }
    }

    protected void txtGrossPremium_TextChanged(object sender, EventArgs e)
    {
        try
        {
            
            decimal _premium = 0;
            txtVAT.Text = "";
            txtTax.Text = "";
            txtNetPremium.Text = "";
            txtAnnualPremium.Text = "";
            lblTax.Text = "0";
            lblVAT.Text = "0";
            lblNetPremium.Text = "0";
            lblAnnualPremium.Text = "0";

            if (decimal.TryParse(txtGrossPremium.Text, out _premium))
            {
                decimal _grossPremium = _premium;

                decimal _netPremium = _premium / 1.07M / 1.004M;

                _netPremium = Math.Floor(Math.Round(_netPremium));

               

                txtNetPremium.Text = _netPremium.ToString("#0.00");

                decimal _tax = 0;

                _tax = Convert.ToDecimal(_netPremium * (0.4M / 100.0M));

                _tax = Math.Ceiling(_tax);

                if (_tax >= 1000)
                {
                    lblTax.Text = _tax.ToString("#,000.00");
                }
                else
                {
                    lblTax.Text = _tax.ToString("#0.00");
                }

                txtTax.Text = _tax.ToString("#0.00");

                decimal _vat = 0;
                _vat = Convert.ToDecimal((_netPremium + _tax) * Convert.ToDecimal(7.0 / 100.0));
                //_vat = Math.Ceiling(_vat);

                if (_vat >= 1000)
                {
                    lblVAT.Text = _vat.ToString("#,000.00");
                }
                else
                {
                    lblVAT.Text = _vat.ToString("#0.00");
                }

                txtVAT.Text = _vat.ToString("#0.00");

                _netPremium = _grossPremium - (_vat + _tax);

                if (_netPremium >= 1000)
                {
                    lblNetPremium.Text = _netPremium.ToString("#,000.00");
                }
                else
                {
                    lblNetPremium.Text = _netPremium.ToString("#0.00");
                }


                decimal _annualPremium = 0;
                decimal _annualPremiumNoDisc = 0;

                _annualPremiumNoDisc = _netPremium + _vat + _tax;

                if (ddlDiscountPercentage.Text != "0" && Convert.ToInt32(ddlDiscountPercentage.Text) > 0)
                {
                    decimal _discountAmount = Convert.ToDecimal((_netPremium * Convert.ToDecimal(Convert.ToDecimal(ddlDiscountPercentage.Text) / 100.0M)));
                    
                    if (_discountAmount >= 1000)
                    {
                        lblDiscountAmount.Text = _discountAmount.ToString("#,000.00");
                    }
                    else
                    {
                        lblDiscountAmount.Text = _discountAmount.ToString("#0.00");
                    }
                    _annualPremium = (_netPremium + _vat + _tax) - _discountAmount;
                }
                else
                {
                    lblDiscountAmount.Text = "0";
                    _annualPremium = _netPremium + _vat + _tax;
                }

                

                if (_annualPremium >= 1000)
                {
                    lblAnnualPremium.Text = _annualPremium.ToString("#,000.00");
                }
                else
                {
                    lblAnnualPremium.Text = _annualPremium.ToString("#0.00");
                }

              
                if (chkCTPL.Checked)
                {
                    _annualPremium = _annualPremium + Convert.ToDecimal(txtCTPL.Text);
                    _annualPremiumNoDisc = _annualPremiumNoDisc + Convert.ToDecimal(txtCTPL.Text);
                }

                txtAnnualPremium.Text = _annualPremium.ToString("#0.00");
                txtFinalAnnualPremium.Text = _annualPremium.ToString("#0.00");
                txtFinalAnnualPremiumNoDisc.Text = _annualPremiumNoDisc.ToString("#0.00");

                
                SixMonthIstallMents();
              
                decimal _InstallmentInterest = 0;
                decimal _InstallmentannualPremiumWD = 0;
                decimal _InstallmentAmountWD = 0;
                decimal _InstallmentLastMonthAmountWD = 0;
                decimal _InstallmentannualPremiumWOD = 0;
                decimal _InstallmentAmountWOD = 0;
                decimal _InstallmentLastMonthAmountWOD = 0;
                if (_annualPremium >= 4000 && ddlBrokerProvider.Text == "29")
                {
                    
                    if (ddlNoofInstallments.Text == "4")
                    {
                        _InstallmentInterest = Convert.ToDecimal(1.032);
                    }
                    else if (ddlNoofInstallments.Text == "6")
                    {
                        _InstallmentInterest = Convert.ToDecimal(1.048);
                    }
                    if (ddlCreditCard.Text == "KBANK")
                    {
                        _InstallmentannualPremiumWD = _annualPremium;
                        _InstallmentannualPremiumWOD = _annualPremiumNoDisc;
                    }
                    else
                    {
                        _InstallmentannualPremiumWD = (_annualPremium * _InstallmentInterest);
                        _InstallmentannualPremiumWOD = (_annualPremiumNoDisc * _InstallmentInterest);
                    }
                  
                }
                else if (_annualPremiumNoDisc >= 4000 && ddlBrokerProvider.Text == "32")
                {
                    if (ddlBrokerCoverType.Text == "10" || ddlBrokerCoverType.Text == "11" || ddlBrokerCoverType.Text == "21")
                    {
                        _InstallmentannualPremiumWD = _annualPremiumNoDisc;
                        _InstallmentannualPremiumWOD = _annualPremiumNoDisc;
                    }
                    else
                    {
                        _InstallmentannualPremiumWD = 0;
                        _InstallmentAmountWD = 0;
                        _InstallmentLastMonthAmountWD = 0;
                        _InstallmentannualPremiumWOD = 0;
                        _InstallmentAmountWOD = 0;
                        _InstallmentLastMonthAmountWOD = 0;
                    }
                }
                else if (_annualPremiumNoDisc >= 4000)
                {
                    _InstallmentannualPremiumWD = _annualPremiumNoDisc;
                    _InstallmentannualPremiumWOD = _annualPremiumNoDisc;
                }
                else
                {
                    _InstallmentannualPremiumWD = 0;
                    _InstallmentAmountWD = 0;
                    _InstallmentLastMonthAmountWD = 0;
                    _InstallmentannualPremiumWOD = 0;
                    _InstallmentAmountWOD = 0;
                    _InstallmentLastMonthAmountWOD = 0;
                }

                Int32 _Installments = Convert.ToInt32(ddlNoofInstallments.Text);
                Int32 _Install = _Installments - 1;
                decimal _TotalInstallMentWD = 0;
                decimal _TotalInstallMentWOD = 0;

                if (ddlBrokerProvider.Text == "29")
                {
                    if (_InstallmentannualPremiumWD > 0 && _Installments > 0)
                    {
                        _InstallmentAmountWD = Math.Ceiling(Convert.ToDecimal(_InstallmentannualPremiumWD / _Installments));
                        _TotalInstallMentWD = Convert.ToDecimal(_InstallmentAmountWD * _Install);
                        _InstallmentLastMonthAmountWD = Convert.ToDecimal(_InstallmentannualPremiumWD - _TotalInstallMentWD);
                    }
                }
                else
                {
                    _InstallmentAmountWD = 0;
                    _TotalInstallMentWD = 0;
                    _InstallmentLastMonthAmountWD = 0;
                }
                if (_InstallmentannualPremiumWOD > 0 && _Installments > 0)
                {
                    _InstallmentAmountWOD = Math.Ceiling(Convert.ToDecimal(_InstallmentannualPremiumWOD / _Installments));
                    _TotalInstallMentWOD = Convert.ToDecimal(_InstallmentAmountWOD * _Install);
                    _InstallmentLastMonthAmountWOD = Convert.ToDecimal(_InstallmentannualPremiumWOD - _TotalInstallMentWOD);
                }

                if (ddlBrokerProvider.Text == "29")
                {
                    lblTotalGrossPremiumWD.Text = _InstallmentannualPremiumWD.ToString("#0.00");
                }
                else
                {
                    lblTotalGrossPremiumWD.Text = Resources.CarInsurance.NoDiscount;
                }
                lblFirstInstallmentWD.Text = _InstallmentAmountWD.ToString("#0.00");
                lblLastInstallmentWD.Text = _InstallmentLastMonthAmountWD.ToString("#0.00");
                lblTotalGrossPremiumWOD.Text = _InstallmentannualPremiumWOD.ToString("#0.00");
                lblFirstInstallmentWOD.Text = _InstallmentAmountWOD.ToString("#0.00");
                lblLastInstallmentWOD.Text = _InstallmentLastMonthAmountWOD.ToString("#0.00");
                lblFirstInstallmentWDdesc.Text = "(1 " + Resources.CarInsurance.To + " " + _Install.ToString() + " " + Resources.CarInsurance.Months + ")";
                lblFirstInstallmentWODdesc.Text = "(1 " + Resources.CarInsurance.To + " " + _Install.ToString() + " " + Resources.CarInsurance.Months + ")";
                //Monthly Installment -- End
            }
        }
        catch (Exception Ex)
        {
            lblPremiumError.Text = Ex.Message;
            Ex = null;
        }
    }

    protected void ddlGarageType_SelectedIndexChanged(object sender, EventArgs e)
    {
        LoadBrokerDefault();//Sop Create method and updated on 16 Nov 2012 from BKK
    }

    protected void ddlDiscountPercentage_SelectedIndexChanged(object sender, EventArgs e)
    {
        txtGrossPremium_TextChanged(sender, e);
        if (ddlDiscountPercentage.Text == "0")
        {
            txtFinalAnnualPremiumNoDisc.Enabled = false;
        }
        else
        {
            txtFinalAnnualPremiumNoDisc.Enabled = true;
        }
    }

    protected void chkCTPL_CheckedChanged(object sender, EventArgs e)
    {
        

        if (chkCTPL.Checked)
        {
            txtCTPL.Enabled = true;
            ddlVehicleBodyType.Enabled = true;
            ddlVehicleBodyType_SelectedIndexChanged(sender, e);
        }
        else
        {
            txtCTPL.Enabled = false;
            ddlVehicleBodyType.Enabled = false;
            txtGrossPremium_TextChanged(sender, e);
        }



    }

    protected void chkCompanyStaff_CheckedChanged(object sender, EventArgs e)
    {
        LoadDiscountPercentageList();

        if (chkCompanyStaff.Checked)
        {
            ListItem _lstTwelve = ddlDiscountPercentage.Items.FindByValue("12");
            if (_lstTwelve != null)
            {
                ddlDiscountPercentage.Text = "12";
            }
            ListItem _lstFifteen = ddlDiscountPercentage.Items.FindByValue("15");
            if (_lstFifteen != null)
            {
                ddlDiscountPercentage.Text = "15";
            }
            if (ddlBrokerProvider.Text == "41")
            {
                ddlDiscountPercentage.Text = "0";
            }
        }
        

        ddlDiscountPercentage_SelectedIndexChanged(sender, e);
    }

    protected void txtCTPL_TextChanged(object sender, EventArgs e)
    {
        txtGrossPremium_TextChanged(sender, e);
    }

    protected void chkConfirmEmail_CheckedChanged(object sender, EventArgs e)
    {
        txtConfirmEmail.Enabled = chkConfirmEmail.Checked;
        btnSendQuotation.Enabled = chkConfirmEmail.Checked;
    }

    protected void chkChangePremium_CheckedChanged(object sender, EventArgs e)
    {
        rfvPremiumChangeComments.Enabled = chkChangePremium.Checked;
        txtFinalAnnualPremiumNoDisc.ReadOnly = !chkChangePremium.Checked;
        txtFinalAnnualPremium.ReadOnly = !chkChangePremium.Checked;
    }

    protected void btnSendQuotation_Click(object sender, EventArgs e)
    {
        try
        {
            NonGGPremiumListPDFOutput _nonGGPdf = CreateNonGGPDFObject();
            string _fileName = _nonGGPdf.GeneratePDF(HttpContext.Current.Session["Language"].ToString());
            if (_fileName != string.Empty)
            {
                FileInfo file = new System.IO.FileInfo(_fileName);
                BrokerPremiumDB _premiumDB = new BrokerPremiumDB();

                if (file.Exists)
                {
                    string[] _file = new string[1];
                    _file[0] = _fileName;

                    string _toemail = txtConfirmEmail.Text.Trim().ToLower();
                    string _ccemail = string.Empty;//Session[General.UserEmail].ToString();
                    if (Session[General.UserRole].ToString() == "100")
                    {
                        _ccemail += Session[General.SMTPReplyTo].ToString();
                    }

                    string _bccemail = CE.Configuration.MyConfigurationManager.GetAppSettingValue("ADMIN");
                    string _customerName = lblName.Text + " " + lblLastName.Text;
                    string imgUrl = "http://" + CE.Configuration.MyConfigurationManager.GetAppSettingValue("LogoPath");
                    string _emailTitle = string.Empty;
                    // "Khun. " + _customerName + ", License Plate: " + txtLicensePlate.Text + " Quotation at " + DateTime.Now.ToString("dd/MMM/yyyy");
                    _emailTitle = "กล้วยๆ.com: ใบเสนอราคาประกันรถยนต์ คุณ " + lblName.Text + " " + txtEditLicensePlate.Text;
                    string mailBody = @"เรียน คุณ <strong>" + _customerName + "</strong><br/><br/>" +
                    "<a href='http://www.gluaygluay.com'>กล้วยๆ.com</a> ขอส่งใบเสนอราคาแบบประกันรถยนต์ให้คุณ " + _customerName + " ได้ทำการเปรียบเทียบและตัดสินใจ<br/> " +
                    "หากท่านต้องการที่จะซื้อหรือต้องการสอบถามรายละเอียดเพิ่มเติม กรุณาติดต่อ <strong>" + Session[General.UserName] + "</strong> ได้ที่หมายเลขโทรศัพท์ <strong>" + Session[General.UserPhoneNo].ToString() + "</strong>";

                    if (Session[General.UserGender] == null)
                    {
                        mailBody += " ขอบพระคุณค่ะ <br/>";
                    }
                    else if (Session[General.UserGender].ToString() == "M")
                    {
                        mailBody += " ขอบพระคุณครับ <br/>";
                    }
                    else
                    {
                        mailBody += " ขอบพระคุณค่ะ <br/>";
                    }

                    mailBody += "<br/>ขอแสดงความนับถือ<br/>" +
                    "<img src='" + imgUrl + "' alt='GluayGluay' width='120' height='100' /><br/>" +
                    "<br/><strong><a href='http://www.gluaygluay.com'>กล้วยๆ.com</a> Support Team</strong><br/>" +
                        //Company Name changed
                    "บริษัท คอมแพร์เอ็กซ์เพรส นายหน้าประกันภัย (ประเทศไทย) จำกัด<br/>" +
                    "เลขทะเบียนนายหน้าประกันวินาศภัยนิติบุคคล เลขที่ ว00016/2553<br/>" +
                    "ชั้น 42 อาคารยูไนเต็ด เซ็นเตอร์ เลขที่ 323 ถนนสีลม แขวงสีลม เขตบางรัก กรุงเทพฯ 10500<br/>" +
                    "โทร. 02-268-8222 โทรสาร 02-266-6339<br/>" +
                    "อีเมล์: support@gluaygluay.com<br/>" +
                    "กด Like เพื่อติดตามเราได้ใน Facebook: www.facebook.com/GGmotor";

                    bool _mailSendingStatus = false;

                    if (Session[General.SMTPAccountName].ToString().Contains("gluaygluay.com"))
                    {
                        _mailSendingStatus = MyMailManager.SendGGMailWithAttach(Session[General.SMTPAccountName].ToString(), Session[General.SMTPAuthCode].ToString(), _toemail, _ccemail, _bccemail, _emailTitle, mailBody, Session[General.SMTPReplyTo].ToString(), _file);
                    }
                    else if (Session[General.SMTPAccountName].ToString().Contains("gmail.com"))
                    {
                        _mailSendingStatus = MyMailManager.SendGGMailWithAttach(Session[General.SMTPAccountName].ToString(), Session[General.SMTPAuthCode].ToString(), _toemail, _ccemail, _bccemail, _emailTitle, mailBody, Session[General.SMTPReplyTo].ToString(), _file);
                    }
                    else
                    {
                        _mailSendingStatus = MyMailManager.SendCXMailWithAttach(Session[General.SMTPAccountName].ToString(), Session[General.SMTPAuthCode].ToString(), _toemail, _ccemail, _bccemail, _emailTitle, mailBody, Session[General.SMTPReplyTo].ToString(), _file);
                    }

                    if (_mailSendingStatus)
                    {
                        if (_premiumDB.SaveQuotationEmail(Convert.ToInt32(txtCarId.Text),
                            Convert.ToInt64(txtCustomerId.Text),
                            Convert.ToInt64(Session[General.UserId].ToString()),
                            txtEditLicensePlate.Text,
                            txtConfirmEmail.Text, 1) > 0)
                        {
                            lblSendQuotationMessage.Text = Resources.General.QuotationSent + " at " + dateTimeNow.ToString("dd/MMM/yyyy hh:mm tt");
                        }
                        else
                        {
                            lblSendQuotationMessage.Text = Resources.General.QuotationSent + " Saving confirm email failed.";
                        }

                        chkConfirmEmail.Checked = false;
                        chkConfirmEmail_CheckedChanged(sender, e);
                        chkConfirmEmail.Enabled = false;
                    }
                    else
                    {
                        
                        lblSendQuotationMessage.Text = Resources.General.QuotationFailed;
                    }
                }
                else
                {
                    lblSendQuotationMessage.Text = "PDF generating failed.";
                    lblSendQuotationMessage.Text += " " + Resources.General.QuotationFailed;
                }
            }
            else
            {
                lblSendQuotationMessage.Text = "PDF generating failed. No item found.";
                lblSendQuotationMessage.Text += " " + Resources.General.QuotationFailed;
            }

        }
        catch (Exception Ex)
        {

            lblSendQuotationMessage.Text = Ex.Message;
        }
    }

    protected void gvCarDetailList_OnSorted(object sender, EventArgs e)
    {
        if (gvCarDetailList.Rows.Count > 0)
        {
            gvCarDetailList.SelectedIndex = -1;
           
            tplCustomerPolicyDetail.Visible = false;

           
            tplResults.Visible = false;

         
            tplCallStatus.Visible = false;

            divCompletedQuoteDetails.Visible = false;
        }
    }

    protected void gvCarDetailList_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (gvCarDetailList.SelectedIndex >= 0)
        {
            ResetAll();
            GridViewRow _row = gvCarDetailList.SelectedRow;
            ShowCarAndCustomerDetails(Convert.ToInt64(txtCustomerId.Text), Convert.ToInt64(_row.Cells[0].Text), Convert.ToInt64(_row.Cells[1].Text));
           
            tplCustomerPolicyDetail.Focus();
        }
    }

    private void ResultsQuotesDataBind()
    {
        GetTempResultTableTwo();
        DataView dv = new DataView();
        if (Session[General.UserId] != null)
        {
            dv = new DataView((DataTable)Cache["CarResult" + Session[General.UserId].ToString() + txtCarId.Text]);
        }
        else
        {
            dv = new DataView((DataTable)Cache["CarResult" + txtCarId.Text]);
        }

        gvCarResult.DataSource = dv;
        gvCarResult.DataBind();
    }

    private void GetTempResultTableTwo()
    {
        MyDatabase _db = new MyDatabase();
        DataTable _dtResult = new DataTable();
        string _spName = "[sprocCarInsuranceResultCallMeSelectItemList]";
        SortedList _sPara = new SortedList();
        //test
        _sPara.Add("@CarId", txtCarId.Text);

        if (Session[General.UserId] != null)
        {
            _sPara.Add("@RefUserId", Session[General.UserId].ToString());
        }
        else
        {
            _sPara.Add("@RefUserId", 0);
        }
        if (Convert.ToInt64(txtAgentId.Text) > 0)
        {
            _sPara.Add("@AgentId", Convert.ToInt64(txtAgentId.Text));
        }
        else
        {
            _sPara.Add("@AgentId", 0);
        }
        _dtResult = _db.GetDataTableBySP(_spName, _sPara);
        


       

        if (Session[General.UserId] != null)
        {
            Cache["CarResult" + Session[General.UserId].ToString() + txtCarId.Text] = _dtResult;
        }
        else
        {
            Cache["CarResult" + txtCarId.Text] = _dtResult;
        }

    }

    protected void gvCarResult_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName.Equals("BuyNow"))
        {
            if (lblCommenceDateStatus.Text == "1" && lblQuoteDateTimeStatus.Text == "1")
            {
                int index = Convert.ToInt32(e.CommandArgument);
                DataKey myData = gvCarResult.DataKeys[index];

                Session[CE.Global.General.CarResultId] = myData[0].ToString();
                Session[CE.Global.General.ProviderCompanyId] = myData[1].ToString();
                Int64 _resultId = Convert.ToInt64(myData[0].ToString());
                Int64 _companyId = Convert.ToInt64(myData[1].ToString());

                Session[General.CallPageStartDateTime] = lblStartDateTime.Text;
                Session[General.BuyNowCarID] = txtCarId.Text;
                
                tplCarList.Visible = false;

                string _buyurl = myData[2].ToString();
                string proposalURL = CE.Configuration.MyConfigurationManager.GetAppSettingValue("CIServerPath");

                proposalURL = proposalURL + "agentlogin.aspx?" + _buyurl;
                ClientScript.RegisterClientScriptBlock(this.GetType(), "OpenBuyNow", "var myRef = window.open('" + proposalURL + "','mywin','left=20,top=20,width=800,height=600,resizable=1,scrollbars=1');", true);
                divBuyNowStatus.Visible = true;
                
               
                tplResults.Visible = false;

               
                tplCallStatus.Visible = false;


                MyDatabase _db = new MyDatabase();
                DataTable _dt = new DataTable("tblSelectedItem");
                SortedList _paraList = new SortedList();
                _paraList.Add("@CarResultID", myData[0].ToString());
                _dt = _db.GetDataTableBySP("sproceCXCRMGetSelectedResultItem", _paraList);
                lblBuyNowStatus.Text = Resources.General.BUYONLINEClickMessage + "<br/>" + Resources.General.CheckAndRefreshMessage;
                if (_dt != null && _dt.Rows.Count > 0)
                {
                    divBuyNowStatusMessage.Visible = true;
                    System.Text.StringBuilder _strBuilder = new System.Text.StringBuilder();
                    _strBuilder.Append("<br/><br/><table width='50%' cellspacing='5' cellpadding='5'>");
                    _strBuilder.Append("<tr><td>" + Resources.CarInsurance.CompanyName + "</td><td>:</td><td><b>" + _dt.Rows[0]["CompanyName"].ToString() + "</b></td></tr>");
                    _strBuilder.Append("<tr><td>" + Resources.General.PremiumAmount + "</td><td>:</td><td><b>" + Convert.ToDouble(_dt.Rows[0]["AnnualPremium"].ToString()).ToString("#,000.00") + "</b></td></tr>");
                    _strBuilder.Append("<tr><td>" + Resources.General.PackageName + "</td><td>:</td><td><b>" + _dt.Rows[0]["CoverTypeDesc"].ToString() + "</b></td></tr>");
                    _strBuilder.Append("</table>");
                    lblBuyNowStatus.Text += _strBuilder.ToString();
                }
            }
            else
            {
               

                ShowQuoteStatusAlert();
            }
        }
        else if (e.CommandName.Equals("Select"))
        {
            int index = Convert.ToInt32(e.CommandArgument);
            DataKey myData = gvCarResult.DataKeys[index];

            Int64 _resultId = Convert.ToInt64(myData[0].ToString());
            Int64 _companyId = Convert.ToInt64(myData[1].ToString());
            CarResultSelectedIndexChanged(_resultId, _companyId);
        }
    }

    private void CarResultSelectedIndexChanged(Int64 CarResultId, Int64 ProviderCompanyId)
    {
        MyDatabase _myDb = new MyDatabase();
        DataTable _dtSeletedItem = new DataTable("tblSelect");
        _dtSeletedItem = _myDb.GetDataTable(@"SELECT P.INSURANCETYPE, P.GarageType, P.IsCTPL, T.* FROM tblCarInsuranceTempResultTH T
	                                                INNER JOIN tblCarPolicy P ON T.CARID = P.CECARID AND P.REFCEUSERID = T.REFCEUSERID 
                                                    Where T.CarID = " + txtCarId.Text + " And T.RefCEUserID = " + txtCustomerId.Text + " And T.CITempResultID = " + CarResultId.ToString() + " And T.ProviderCompanyID = " + ProviderCompanyId.ToString());

        if (_dtSeletedItem != null && _dtSeletedItem.Rows.Count > 0)
        {
            btnNewPremium_Click(null, null);
            float _totalVMI = Convert.ToSingle(_dtSeletedItem.Rows[0]["TotalVMI"].ToString());
            ddlBrokerProvider.Text = ProviderCompanyId.ToString();
            ddlBrokerProvider_SelectedIndexChanged(null, null);
            ddlBrokerCoverType.Text = _dtSeletedItem.Rows[0]["INSURANCETYPE"].ToString();
           

            if (txtPremiumId.Text == "0")
            {
                ddlGarageType.Text = _dtSeletedItem.Rows[0]["GarageType"].ToString();


                if (_dtSeletedItem.Rows[0]["TPBIA"] != DBNull.Value)
                {
                    txtTPBIA.Text = Convert.ToSingle(_dtSeletedItem.Rows[0]["TPBIA"].ToString()).ToString("#,000");
                }
                else
                {
                    txtTPBIA.Text = "N/A";
                }

                if (_dtSeletedItem.Rows[0]["TPBIP"] != DBNull.Value)
                {
                    txtTPBIP.Text = Convert.ToSingle(_dtSeletedItem.Rows[0]["TPBIP"].ToString()).ToString("#,000");
                }
                else
                {
                    txtTPBIP.Text = "N/A";
                }

                if (_dtSeletedItem.Rows[0]["TPPD"] != DBNull.Value)
                {
                    txtTPPD.Text = Convert.ToSingle(_dtSeletedItem.Rows[0]["TPPD"].ToString()).ToString("#,000");
                }
                else
                {
                    txtTPPD.Text = "N/A";
                }

                if (_dtSeletedItem.Rows[0]["DEC"] != DBNull.Value)
                {
                    txtDeductible.Text = Convert.ToSingle(_dtSeletedItem.Rows[0]["DEC"].ToString()).ToString("#0");
                }

                if (_dtSeletedItem.Rows[0]["PADriver"] != DBNull.Value)
                {
                    txtPA.Text = Convert.ToSingle(_dtSeletedItem.Rows[0]["PADriver"].ToString()).ToString("#,000");
                }
                else
                {
                    txtPA.Text = "N/A";
                }

                if (_dtSeletedItem.Rows[0]["BailBond"] != DBNull.Value)
                {
                    txtBailBond.Text = Convert.ToSingle(_dtSeletedItem.Rows[0]["BailBond"].ToString()).ToString("#,000");
                }
                else
                {
                    txtBailBond.Text = "N/A";
                }

                if (_dtSeletedItem.Rows[0]["Fire"] != DBNull.Value)
                {
                    txtFireTheft.Text = Convert.ToSingle(_dtSeletedItem.Rows[0]["Fire"].ToString()).ToString("#,000");
                }
                else
                {
                    txtFireTheft.Text = "N/A";
                }

               

                if (_dtSeletedItem.Rows[0]["SumInsured"] != DBNull.Value)
                {
                    txtOwnDamage.Text = Convert.ToSingle(_dtSeletedItem.Rows[0]["SumInsured"].ToString()).ToString("#,000");
                }
                else
                {
                    txtOwnDamage.Text = "N/A";
                }

                if (_dtSeletedItem.Rows[0]["IsFloodCover"] != DBNull.Value)
                {
                    if (_dtSeletedItem.Rows[0]["IsFloodCover"].ToString() == "1")
                    {
                        txtFloodCoverAmount.Text = txtOwnDamage.Text;
                    }
                    else
                    {
                        txtFloodCoverAmount.Text = "N/A";
                    }
                }
                txtGrossPremium.Text = _totalVMI.ToString("#000.00");

                float _totalCMI = 0.0f;
                if (_dtSeletedItem.Rows[0]["IsCTPL"] != DBNull.Value)
                {
                    if (_dtSeletedItem.Rows[0]["IsCTPL"].ToString().ToLower() == "true")
                    {
                        _totalCMI = Convert.ToSingle(_dtSeletedItem.Rows[0]["TotalCMI"].ToString());
                        chkCTPL.Checked = true;
                    }
                    else
                    {
                        chkCTPL.Checked = false;
                    }
                }

                txtCTPL.Text = _totalCMI.ToString("#,000.00");
                txtGrossPremium_TextChanged(null, null);

                
            }
        }
    }


    private void ShowQuoteStatusAlert()
    {
        if (lblCommenceDateStatus.Text == "0" || lblQuoteDateTimeStatus.Text == "0")
        {
            ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('" + lblQuoteStatusMessage.Text + "');", true);
        }
    }

    protected void btnBuyNowRefresh_Click(object sender, EventArgs e)
    {
        Session[General.CallPageStartDateTime] = lblStartDateTime.Text;
        lblResetUrl.Text = lblResetUrl.Text.Replace("&buynowrefresh=true", "");
        Response.Redirect(lblResetUrl.Text + "&buynowrefresh=true");
    }

    protected void gvCarResult_RowCreated(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.Header)
        {
            foreach (TableCell cell in e.Row.Cells)
            {
                if (cell.HasControls())
                {
                    LinkButton button = cell.Controls[0] as LinkButton;
                    if (button != null)
                    {
                        Image imageSort = new Image();
                        imageSort.ImageUrl = "~/OLD/images/icons/clear.gif";
                        HtmlGenericControl gv = new HtmlGenericControl("div");
                        Label lnkName = new Label();
                        lnkName.Text = button.Text;

                        if (ViewState["SortExpression"] != null && ViewState["SortExpression"].ToString() == button.CommandArgument.ToString())
                        {
                            if (ViewState["SortOrder"] != null && ViewState["SortOrder"].ToString() == SortDirection.Descending.ToString())
                            {
                                imageSort.ImageUrl = "~/OLD/images/icons/Sort_Down.gif";
                            }
                            else
                            {
                                imageSort.ImageUrl = "~/OLD/images/icons/Sort_Up.gif";
                            }
                        }
                        gv.Controls.Add(lnkName);
                        gv.Controls.Add(imageSort);
                        button.Controls.Add(gv);
                    }
                }
            }

            //Creat Custome Header
            GridView HeaderGrid = (GridView)sender;
            GridViewRow HeaderGridRow =
            new GridViewRow(0, 0, DataControlRowType.Header,
            DataControlRowState.Insert);

            TableCell HeaderCell = new TableCell();
            HeaderCell.Text = "";
            HeaderCell.HorizontalAlign = HorizontalAlign.Center;
            HeaderCell.ColumnSpan = 3;
            HeaderGridRow.Cells.Add(HeaderCell);

            HeaderCell = new TableCell();
            HeaderCell.Text = "<img src='../../images/arrows/arrow-down.png\'  />" + Resources.CarInsuranceResultPage.OwnDamage + "<img src=\"../../images/arrows/arrow-down.png\" align=\"absmiddle\" alt=\"\" />";
            HeaderCell.Font.Bold = true;
            HeaderCell.ControlStyle.CssClass = "green_top";
            HeaderCell.HorizontalAlign = HorizontalAlign.Center;
            HeaderCell.ColumnSpan = 2;
            HeaderGridRow.Cells.Add(HeaderCell);

            HeaderCell = new TableCell();
            HeaderCell.Text = "<img src=\"../../images/arrows/arrow-down.png\" align=\"absmiddle\" alt=\"\" /> " + Resources.CarInsuranceResultPage.ThirdPartyLiability + "<img src=\"../../images/arrows/arrow-down.png\" align=\"absmiddle\" alt=\"\" /><br/>" + Resources.CarInsuranceResultPage.PerAccident;
            HeaderCell.Font.Bold = true;
            HeaderCell.ControlStyle.CssClass = "blue_top";
            HeaderCell.HorizontalAlign = HorizontalAlign.Center;
            HeaderCell.ColumnSpan = 3;
            HeaderGridRow.Cells.Add(HeaderCell);

            HeaderCell = new TableCell();
            HeaderCell.Text = "<img src=\"../../images/arrows/arrow-down.png\" align=\"absmiddle\" alt=\"\" />" + Resources.CarInsuranceResultPage.AdditionalCovers + "<img src=\"../../images/arrows/arrow-down.png\" align=\"absmiddle\" alt=\"\" />";
            HeaderCell.Font.Bold = true;
            HeaderCell.ControlStyle.CssClass = "gold_top";
            HeaderCell.HorizontalAlign = HorizontalAlign.Center;
            HeaderCell.ColumnSpan = 3;
            HeaderGridRow.Cells.Add(HeaderCell);

            HeaderCell = new TableCell();
            HeaderCell.Text = "";
            HeaderCell.HorizontalAlign = HorizontalAlign.Center;
            
            HeaderGridRow.Cells.Add(HeaderCell);

            gvCarResult.Controls[0].Controls.AddAt
            (0, HeaderGridRow);
        }

        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            ImageButton ibtBuyNow = (ImageButton)e.Row.FindControl("ibtBuyNow");

            ibtBuyNow.CommandArgument = e.Row.RowIndex.ToString();

            HyperLink _lnkTest = new HyperLink();
            ibtBuyNow.OnClientClick = "javascript:return confirm('" + Resources.General.ConfirmBUYONLINEMessage + "');";
            _lnkTest = null;

        }
    }

    protected void gvCarResult_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        //HIDE
        //For Thailand
        if (e.Row.RowType == DataControlRowType.DataRow)
        {


            string _callCarProviderId = "";

            string _companyId = DataBinder.Eval(e.Row.DataItem, "ProviderCompanyId").ToString();
            ImageButton btnApplyNow = (ImageButton)e.Row.FindControl("ibtBuyNow");
            btnApplyNow.CommandArgument = e.Row.RowIndex.ToString();

            _callCarProviderId = _companyId;

            if (e.Row.DataItem != null)
            {
                _currentRow += 1;
                
            }

            HtmlGenericControl divFrame = new HtmlGenericControl("div");
            divFrame.Attributes.Add("id", "framework_moreinfo");

            HtmlGenericControl divContainer = new HtmlGenericControl("div");
            divContainer.Attributes.Add("id", "container_moreinfo");

            HtmlGenericControl divContent = new HtmlGenericControl("div");
            divContent.Attributes.Add("id", "content_moreinfo");

            Label lblPolicyInfoId = new Label();
            lblPolicyInfoId = (Label)e.Row.FindControl("lblPolicyInfoId");
            object _objPolicyinfoId = 4;//DataBinder.Eval(e.Row.DataItem, "NInfo3");

            Label lblPromoId = new Label();
            lblPromoId = (Label)e.Row.FindControl("lblPromoId");
            object _objPromoId = 11;//DataBinder.Eval(e.Row.DataItem, "NInfo2");

            Label lblPolicyId = new Label();
            lblPolicyId = (Label)e.Row.FindControl("lblPolicyId");
            object _objPolicyId = 5;//DataBinder.Eval(e.Row.DataItem, "NInfo1");

           


            //Company Logo and Cover Type
            Label lblCoverTypeDesc = (Label)e.Row.FindControl("lblPackageName");
            Image imgCompanyLogo = (Image)e.Row.FindControl("imgCompanyLogo");




            string _logoUrl = DataBinder.Eval(e.Row.DataItem, "CompanyLogoServerUrl").ToString();
            string _coverTypeDesc = DataBinder.Eval(e.Row.DataItem, "PackageName").ToString().Trim();

            imgCompanyLogo.ImageUrl = "~" + _logoUrl;
            imgCompanyLogo.ToolTip = _coverTypeDesc;
            lblCoverTypeDesc.Text = _coverTypeDesc;
          

            ////CTPL
            Label lblCTPL = (Label)e.Row.FindControl("lblCTPL");
            Label lblCTPLSymbol = (Label)e.Row.FindControl("lblCTPLSymbol");
            Image imgCTPL = (Image)e.Row.FindControl("imgCTPL");
            string _totalCMI = DataBinder.Eval(e.Row.DataItem, "TotalCMI").ToString().Trim();

            if (_totalCMI != null && _totalCMI != string.Empty && Convert.ToSingle(_totalCMI) > 0.0f)
            {
                imgCTPL.Visible = false;
                lblCTPL.Text = _totalCMI;
                lblCTPL.Visible = true;
                lblCTPLSymbol.Visible = true;
            }
            else
            {
                imgCTPL.Visible = true;
                lblCTPL.Text = "0";
                lblCTPL.Visible = false;
                lblCTPLSymbol.Visible = false;
            }
            ////END CTPL

            //// DEC
            Label lblDEC = (Label)e.Row.FindControl("lblDEC");
            Label lblDECSymbol = (Label)e.Row.FindControl("lblDECSymbol");
            Label lblDECZero = (Label)e.Row.FindControl("lblDECZero");
            string _DEC = DataBinder.Eval(e.Row.DataItem, "DEC").ToString().Trim();

            if (_DEC != null && _DEC != string.Empty && Convert.ToSingle(_DEC) > 0.0f)
            {
                lblDECZero.Visible = false;
                lblDEC.Text = _DEC;
                lblDEC.Visible = true;
                lblDECSymbol.Visible = true;
            }
            else
            {
                lblDECZero.Visible = true;
                lblDEC.Text = "0";
                lblDEC.Visible = false;
                lblDECSymbol.Visible = false;
            }
            //// END DEC

            ///SUM INSURED OR OWN DAMAGE FIRE OR THIEF
            Label lblSumInsured = (Label)e.Row.FindControl("lblSumInsured");
            Label lblSumInsuredSymbol = (Label)e.Row.FindControl("lblSumInsuredSymbol");
            Image imgSumInsured = (Image)e.Row.FindControl("imgSumInsured");
            string _sumInsured = DataBinder.Eval(e.Row.DataItem, "SumInsured").ToString().Trim();

            if (_sumInsured != null && _sumInsured != string.Empty && Convert.ToSingle(_sumInsured) > 0.0f)
            {
                imgSumInsured.Visible = false;
                lblSumInsured.Text = Convert.ToInt32(_sumInsured).ToString("#,000"); //_sumInsured;
                lblSumInsured.Visible = true;
                lblSumInsuredSymbol.Visible = true;
            }
            else
            {
                imgSumInsured.Visible = true;
                lblSumInsured.Text = "0";
                lblSumInsured.Visible = false;
                lblSumInsuredSymbol.Visible = false;
            }
            ///END SUM INSURED OR OWN DAMAGE FIRE OR THIEF

            //GARAGE

           
            HyperLink hplnkWorkshop = (HyperLink)e.Row.FindControl("hplWorkshopLink");
           
            hplnkWorkshop.Target = "_blank";
            hplnkWorkshop.Font.Bold = true;
            if (_companyId == "11")
            {
                // "Allianz C.P";
                if (HttpContext.Current.Session["Language"].ToString() == "th-TH")
                {
                    hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.AllianceWorkshopTH");
                }
                else
                {
                    hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.AllianceWorkshopEN");
                }

            }
            else if (_companyId == "12")
            {
                //lblPromo.Text = "MSIG";
                if (HttpContext.Current.Session["Language"].ToString() == "th-TH")
                {
                    hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.MSIGWorkshopTH");
                }
                else
                {
                    hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.MSIGWorkshopEN");
                }
            }
            else if (_companyId == "16")
            {
                //lblPromo.Text = "AXA";
                if (HttpContext.Current.Session["Language"].ToString() == "th-TH")
                {
                    hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.AXAWorkshopTH");
                }
                else
                {
                    hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.AXAWorkshopEN");
                }
            }
            else if (_companyId == "29")
            {
                //lblPromo.Text = "LMG Insurance";
                if (HttpContext.Current.Session["Language"].ToString() == "th-TH")
                {
                    hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.LMGWorkshopTH");
                }
                else
                {
                    hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.LMGWorkshopEN");
                }
            }
            else if (_companyId == "31")
            {
                //lblPromo.Text = "Chartis";
                if (HttpContext.Current.Session["Language"].ToString() == "th-TH")
                {
                    hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.ChartisWorkshopTH");
                }
                else
                {
                    hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.ChartisWorkshopEN");
                }
            }
            else if (_companyId == "32")
            {
                //lblPromo.Text = "Bangkok Insurance";
                if (HttpContext.Current.Session["Language"].ToString() == "th-TH")
                {
                    hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.BKIWorkshopTH");
                }
                else
                {
                    hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.BKIWorkshopEN");
                }
            }
            else if (_companyId == "33")
            {
                //lblPromo.Text = "MTI Insurance";
                if (HttpContext.Current.Session["Language"].ToString() == "th-TH")
                {
                    hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.MTIWorkshopTH");
                }
                else
                {
                    hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.MTIWorkshopEN");
                }
            }
            else if (_companyId == "35")
            {
                //lblPromo.Text = "KPI Insurance";
                if (HttpContext.Current.Session["Language"].ToString() == "th-TH")
                {
                    hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.KPIWorkshopTH");
                }
                else
                {
                    hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.KPIWorkshopTH");
                }
            }
            else if (_companyId == "39")
            {
                //lblPromo.Text = "KPI Insurance";
                if (HttpContext.Current.Session["Language"].ToString() == "th-TH")
                {
                    hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.MittareWorkshopTH");
                }
                else
                {
                    hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.MittareWorkshopEN");
                }
            }
            else if (_companyId == "41")
            {
                //lblPromo.Text = "Kurnia Insurance";
                if (HttpContext.Current.Session["Language"].ToString() == "th-TH")
                {
                    hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.KurniaWorkShopTH");
                }
                else
                {
                    hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.KurniaWorkShopTH");
                }
            }
            else if (_companyId == "43")
            {
                //lblPromo.Text = "SMK Insurance";
                if (HttpContext.Current.Session["Language"].ToString() == "th-TH")
                {
                    hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.SMKWorkShopTH");
                }
                else
                {
                    hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.SMKWorkShopEN");
                }
            }
            else if (_companyId == "45")
            {
                //lblPromo.Text = "Viriyah Insurance";
                if (HttpContext.Current.Session["Language"].ToString() == "th-TH")
                {
                    hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.ViriyahWorkshopTH");
                }
                else
                {
                    hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.ViriyahWorkshopEN");
                }
            }
            else if (_companyId == "46")
            {
                //lblPromo.Text = "TMS Insurance";
                if (HttpContext.Current.Session["Language"].ToString() == "th-TH")
                {
                    hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.TokioWorkShopTH");
                }
                else
                {
                    hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.TokioWorkShopEN");
                }
            }
            else if (_companyId == "58")
            {
                //lblPromo.Text = "ThaiVivat Insurance";
                if (HttpContext.Current.Session["Language"].ToString() == "th-TH")
                {
                    hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.ThaivivatWorkshopTH");
                }
                else
                {
                    hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.ThaivivatWorkshopEN");
                }
            }

            //END GARAGE
        }

    }

    private void SetGVCarDetailSelectedIndex(Int64 CarID)
    {
        bool _foundStatus = false;
        foreach (GridViewRow myRow in gvCarDetailList.Rows)
        {
            Int64 _carid = Convert.ToInt64(gvCarDetailList.DataKeys[myRow.RowIndex][0]);
           
            if (_carid == CarID)
            {
                gvCarDetailList.SelectedIndex = myRow.RowIndex;
                gvCarDetailList_SelectedIndexChanged(null, null);
                _foundStatus = true;
                break;
            }
        }

        if (_foundStatus == false)
        {
            gvCarDetailList.SelectedIndex = 0;
            gvCarDetailList_SelectedIndexChanged(null, null);
        }
    }

    private bool SendOrderConfirmation()
    {
        bool _retVal = false;

        CE.Database.MyDatabase _db = new CE.Database.MyDatabase();

        string _ccemail = string.Empty;

        

        if (Session[General.UserRole].ToString() == "100")
        {
            _ccemail += Session[General.SMTPReplyTo].ToString();
        }

        string _bccemail = string.Empty;

       

        System.Data.DataTable _dtSeletectItem = new System.Data.DataTable("SelectedResultItem");
        _dtSeletectItem = _db.GetDataTable("select b.CompanyName, p.* from tblCXBrokerPremium p INNER JOIN tblCXBrokerProvider b "
                                           + " ON p.CXBrokerProviderId = b.CXBrokerProviderId WHERE p.CECarId = " + txtCarId.Text + " And p.CustomerId = " + txtCustomerId.Text + " And p.SelectedStatus = 1");

        if (_dtSeletectItem != null && _dtSeletectItem.Rows.Count > 0)
        {
            string _InsuranceType = "";
            switch (_dtSeletectItem.Rows[0]["ProviderCoverTypeID"].ToString())
            {

                case "10":
                    _InsuranceType = Resources.CarInsurance.Insurance_ClassOne;
                    break;
                case "11":
                    _InsuranceType = Resources.CarInsurance.Insurance_ClassOneLowCost;
                    break;
                case "21":
                    _InsuranceType = Resources.CarInsurance.Insurance_ClassTwoPlus;
                    break;
                case "31":
                    _InsuranceType = Resources.CarInsurance.Insurance_ClassThreePlus;
                    break;
                case "30":
                    _InsuranceType = Resources.CarInsurance.Insurance_ClassThree;
                    break;
            }

            string _strCXLive = CE.Configuration.MyConfigurationManager.GetAppSettingValue("CXCRMIsCXLive");
            string _strVirtualDir = CE.Configuration.MyConfigurationManager.GetAppSettingValue("VirtualDir");

            string _emailTo = txtConfirmEmail.Text;
            string _customername = lblName.Text + " " + lblLastName.Text;
            string _emailSubject = Resources.EmailMessage.Subject; // "Your Car Insurance Quotes on CompareXpress(Thailand)";
            string _mailBody = "";

            Uri myUri = new Uri(HttpContext.Current.Request.Url.ToString());
            string _currentDomainUrl = "http://" + HttpContext.Current.Request.Url.Host.ToString();
            if (_strCXLive == "2")
            {
                _currentDomainUrl = "http://" + myUri.Authority;
            }
            else
            {
                _currentDomainUrl = "http://" + myUri.Host;
            }

            _currentDomainUrl = _currentDomainUrl + "/" + _strVirtualDir;

            string imgLogoUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("LogoPath");

            _mailBody = "<body class='email_body'>";
            _mailBody += "<style type='text/css'>";
            _mailBody += ".email_body {background: white;margin: 0;padding: 0;color: #4c4c4c;font-family: Arial, Helvetica, sans-serif;font-size: 0.85em;}";
            _mailBody += "a {text-decoration:underline;color:#2c95cc;} ";
            _mailBody += "#email_container {margin:0 auto;padding:20px;width:600px; height:auto;} ";
            _mailBody += "#email_body {width:100%; text-align: left !important;} ";
            _mailBody += ".email_pad10px {padding:10px;} ";
            _mailBody += ".email_results td {width:33%;} ";
            _mailBody += "</style>";
            _mailBody += "<center> <br /><br />";

            _mailBody += "<table cellpadding='0' cellspacing='0' border='0' width='570'>";
            _mailBody += "<tr><td width='570'><table cellspacing='0' cellpadding='0' width='100%' border='0'>";
            _mailBody += "<tr><td width='50%' valign='top'><strong>" + Resources.Proposal.OrderConfirmation + "</strong><br /><br />";
            _mailBody += Resources.Proposal.ThankYou + "<br/><br/>";
            _mailBody += "<br/><strong>" + Resources.Proposal.OrderNo + " </strong>" + _dtSeletectItem.Rows[0]["Info1"].ToString() + "</td><td width='50%' align='right' valign='top'><img src='" + imgLogoUrl + "' width='130' height='99'/></td></tr>";
            _mailBody += "</table>";

            _mailBody += "<table cellspacing='0' cellpadding='2' width='570' border='0'>";
            _mailBody += " <tr><td width='50%' valign='top'>" + Resources.Proposal.InsuranceType + " " + _InsuranceType + "</td><td width='50%;' valign='top'>&nbsp;</td>";
            _mailBody += "</tr><tr><td valign='top'>" + Resources.Proposal.RefNo + ": " + _dtSeletectItem.Rows[0]["Info2"].ToString() + "</td><td valign='top'>" + Resources.Proposal.OrderDate + ": " + dateTimeNow.ToString("dd/MMM/yyyy") + "</td></tr>";
            _mailBody += "<tr><td valign='top'>" + Resources.CarInsurance.FullName + ": " + _customername + "</td><td valign='top'>" + Resources.Proposal.LicensePlateNo + ": " + txtEditLicensePlate.Text + "</td></tr>";
            _mailBody += "<tr><td valign='top'>" + Resources.Proposal.MakeModel + ": " + lblCarMakeModel.Text + "</td><td valign='top'>" + Resources.Proposal.CarYear + ": " + lblRegYear.Text + "</td></tr>";

            string _garageType = Resources.CarInsurance.Garage_Authorized;

            if (_dtSeletectItem.Rows[0]["Workshop"].ToString() == "1")
            {
                _garageType = Resources.CarInsurance.Garage_Authorized;
            }
            else if (_dtSeletectItem.Rows[0]["Workshop"].ToString() == "2")
            {
                _garageType = Resources.CarInsurance.Garage_Dealer;
            }

            _mailBody += "<tr><td valign='top'>" + Resources.Proposal.GarageType + ": " + _garageType + "</td><td valign='top'>" + Resources.Proposal.NamedDrivers + ": " + ddlEditNamedDriver.Text + "</td></tr>";
            _mailBody += "<tr><td valign='top'>" + Resources.Proposal.PolicyStartDate + ": " + lblEditCoverCommencementDate.Text + " </td><td valign='top'></td></tr>";
            _mailBody += "</table> <br /><br />";

            _mailBody += "<table cellpadding='5' cellspacing='0' border='0' width='100%' class='table_details'>";


            string _providercompanyid = _dtSeletectItem.Rows[0]["CXBrokerProviderID"].ToString();
            //logo
            string logourl = CE.Global.General.GetProviderCompanyLogo(_providercompanyid);

            _mailBody += "<tr>";
            _mailBody += "<td width='45%'></td>";
            _mailBody += "<td width='55%' align='center' style='background:#e0e0e0; border-bottom:white 1px dashed;'><img src='" + _currentDomainUrl + logourl + "' width='130' style='padding:3px;'/></td>";
            _mailBody += "</tr>";

            string insurername = _dtSeletectItem.Rows[0]["CompanyName"].ToString();

            //insurer name
            _mailBody += "<tr>";
            _mailBody += "<td><strong>" + Resources.CarInsuranceResultPage.Insurer + "</strong></td>";
            _mailBody += "<td align='center' style='background:#d5d5d5; font-weight:bold; color:black;'><strong>" + insurername + "</strong></td>";
            _mailBody += "</tr>";

            

            //Deductible  
            _mailBody += "<tr>";
            _mailBody += "<td style='border-bottom:1px solid #ccc;'><strong>" + Resources.CarInsuranceResultPage.DEC + "</strong></td>";
            float _fDEC = 0.0f;
            string _strDEC = _dtSeletectItem.Rows[0]["DEC"].ToString();
            string deductible = "";
            if (float.TryParse(_strDEC, out _fDEC) && _fDEC > 0)
            {
                deductible = String.Format("{0:0,0.00}", _fDEC);
            }
            else
            {
                deductible = Resources.CarInsuranceResultPage.Waived;  //"<img src='" + _currentDomainUrl + "/images/icon/X.png' width='16' alt='NA' />";
            }
            _mailBody += "<td align='center' style='background:#c5c5c5' >" + deductible + "</td>";
            _mailBody += "</tr>";

            
            string suminsured = _dtSeletectItem.Rows[0]["OwnDamage"].ToString();

            if (suminsured == "0")
            {
                suminsured = "<img src='" + _currentDomainUrl + "/images/icons/X.png' width='16' alt='NA' />";
            }
            else
            {
                float _sumInsured = 0.0f;
                if (float.TryParse(suminsured, out _sumInsured))
                {
                    suminsured = String.Format("{0:0,0}", _sumInsured);
                }
            }
            //Own Damage
            _mailBody += "<tr>";
            _mailBody += "<td><strong>" + Resources.CarInsuranceResultPage.OwnDamage + "</strong></td>";
            _mailBody += "<td align='center' style='background:#d5d5d5' >" + suminsured + "</td>";
            _mailBody += "</tr>";

            //Fire
            string firetheft = _dtSeletectItem.Rows[0]["FireTheft"].ToString();
            if (firetheft == "0")
            {
                firetheft = "<img src='" + _currentDomainUrl + "/images/icons/X.png' width='16' alt='NA' />";
            }
            _mailBody += "<tr>";
            _mailBody += "<td><strong>" + Resources.CarInsuranceResultPage.FireTheft + "</strong></td>";
            _mailBody += "<td align='center' style='background:#c5c5c5' >" + firetheft + "</td>";
            _mailBody += "</tr>";

           

            //TPPD
            _mailBody += "<tr>";
            _mailBody += "<td><strong>" + Resources.CarInsuranceResultPage.TPPD + "</strong></td>";
            _mailBody += "<td align='center' style='background:#d5d5d5' >" + _dtSeletectItem.Rows[0]["TPPD"].ToString() + "</td>";
            _mailBody += "</tr>";

            //TPBIA
            _mailBody += "<tr>";
            _mailBody += "<td style='border-bottom:1px solid #ccc;'><strong>" + Resources.CarInsuranceResultPage.TPBIA + "</strong></td>";
            _mailBody += "<td align='center' style='background:#c5c5c5' >" + _dtSeletectItem.Rows[0]["TPBIA"].ToString() + "</td>";
            _mailBody += "</tr>";

            //TPBIP
            _mailBody += "<tr>";
            _mailBody += "<td style='border-bottom:1px solid #ccc;'><strong>" + Resources.CarInsuranceResultPage.TPBIP + "</strong></td>";
            _mailBody += "<td align='center' style='background:#d5d5d5' >" + _dtSeletectItem.Rows[0]["TPBIP"].ToString() + "</td>";
            _mailBody += "</tr>";

            //PA Driver
            _mailBody += "<tr>";
            _mailBody += "<td style='border-bottom:1px solid #ccc;'><strong>" + Resources.CarInsuranceResultPage.PADriver + "</strong></td>";
            _mailBody += "<td align='center' style='background:#c5c5c5' >" + _dtSeletectItem.Rows[0]["PADriver"].ToString() + "</td>";
            _mailBody += "</tr>";


            string _MedicalExpense = _dtSeletectItem.Rows[0]["MedicalExpense"].ToString();
            string medicalExpense = "";

            if (_MedicalExpense == string.Empty || _MedicalExpense == "0")
            {
                medicalExpense = "<img src='" + _currentDomainUrl + "/images/icons/X.png' width='16' alt='NA' />";
            }
            else
            {
                medicalExpense = _MedicalExpense;
            }

            //Medical Expense
            _mailBody += "<tr>";
            _mailBody += "<td><strong>" + Resources.CarInsuranceResultPage.MED + "</strong></td>";
            _mailBody += "<td align='center' style='background:#d5d5d5' >" + medicalExpense + "</td>";
            _mailBody += "</tr>";

            //BB
            _mailBody += "<tr>";
            _mailBody += "<td><strong>" + Resources.CarInsuranceResultPage.BailBond + "</strong></td>";
            _mailBody += "<td align='center' style='background:#c5c5c5' >" + String.Format("{0:#,0}", Convert.ToSingle(_dtSeletectItem.Rows[0]["BailBond"].ToString())) + "</td>";
            _mailBody += "</tr>";

            //Flood Cover
            if (_dtSeletectItem.Rows[0]["Info5"] != DBNull.Value)
            {
                float _floodCover = 0.0f;

                _mailBody += "<tr>";
                _mailBody += "<td style='border-bottom:1px solid #ccc;'><strong>" + Resources.CarInsuranceResultPage.FloodCover + "</strong></td>";
                if (float.TryParse(_dtSeletectItem.Rows[0]["Info5"].ToString(), out _floodCover))
                {
                    _mailBody += "<td align='center' style='background:#d5d5d5' >" + String.Format("{0:#,0}", _floodCover) + "</td>";
                }
                else
                {
                    _mailBody += "<td align='center' style='background:#d5d5d5' >" + _dtSeletectItem.Rows[0]["Info5"].ToString() + "</td>";
                }
                _mailBody += "</tr>";
            }

            string _TotalVMI = _dtSeletectItem.Rows[0]["TotalVMI"].ToString();
            string _TotalCMI = _dtSeletectItem.Rows[0]["TotalCMI"].ToString();
            string _FinalAnnualPremium = _dtSeletectItem.Rows[0]["FinalAnnualPremium"].ToString();
            string _FinalAnnualPremiumNoDisc = string.Empty;


            //Sakthi Change on 04 Dec 2012 -- Start
            Int64 _strBrokerProvider = 0;
            string _strPaymentOption = "FP";
            string _strMonthlyInstallment = "0.00";
            Int32 _Installments = 3;
            Int32 _Install = _Installments - 1;
            string _strFirstInstallmentDesc = "";
            string _strLastInstallmentDesc = "";
            string _InerestFree = "<img src='" + _currentDomainUrl + "/images/icons/tick.gif' width='16' alt='NA' />";
            string _BankCode = "BKK";

            if (_dtSeletectItem.Rows[0]["CXBrokerProviderId"] != DBNull.Value && _dtSeletectItem.Rows[0]["CXBrokerProviderId"].ToString() != string.Empty)
            {
                _strBrokerProvider = Convert.ToInt32(_dtSeletectItem.Rows[0]["CXBrokerProviderId"].ToString());
            }

            if (_dtSeletectItem.Rows[0]["PaymentOption"] != DBNull.Value && _dtSeletectItem.Rows[0]["PaymentOption"].ToString() != string.Empty)
            {
                _strPaymentOption = _dtSeletectItem.Rows[0]["PaymentOption"].ToString();
            }

            if (_dtSeletectItem.Rows[0]["NoofInstallMent"] != DBNull.Value && _dtSeletectItem.Rows[0]["NoofInstallMent"].ToString() != string.Empty)
            {
                _Installments = Convert.ToInt32(_dtSeletectItem.Rows[0]["NoofInstallMent"].ToString());
            }

            if (_dtSeletectItem.Rows[0]["Bank"] != DBNull.Value && _dtSeletectItem.Rows[0]["Bank"].ToString() != string.Empty)
            {
                _BankCode = _dtSeletectItem.Rows[0]["Bank"].ToString();
            }
            _strFirstInstallmentDesc = "(1 " + Resources.CarInsurance.To + " " + _Install.ToString() + " " + Resources.CarInsurance.Months + ")";
            _strLastInstallmentDesc = Resources.CarInsurance.LastMonthInstallment;

            if (_strBrokerProvider == 29)
            {
                if (_BankCode == "KBANK")
                {
                    _InerestFree = "<img src='" + _currentDomainUrl + "/images/icons/tick.gif' width='16' alt='NA' />";
                }
                else
                {
                    _InerestFree = "<img src='" + _currentDomainUrl + "/images/icons/X.png' width='16' alt='NA' />";
                }
                _strMonthlyInstallment = (Convert.ToSingle(_dtSeletectItem.Rows[0]["InstallmentAmountWD"].ToString())).ToString("#,000.00");
            }
            else
            {
                _strMonthlyInstallment = (Convert.ToSingle(_dtSeletectItem.Rows[0]["InstallmentAmountWOD"].ToString())).ToString("#,000.00");
            }
            //Sakthi Change on 04 Dec 2012 -- End

            if (_dtSeletectItem.Rows[0]["FInfo1"] != DBNull.Value)
            {
                _FinalAnnualPremiumNoDisc = _dtSeletectItem.Rows[0]["FInfo1"].ToString();

                //Annual Premium (tax + duty)
                _mailBody += "<tr>";
                _mailBody += "<td align='left' style='border-bottom:1px solid #ccc;' valign='bottom' ><strong>" + Resources.CarInsuranceResultPage.AnnualPremium + "</strong></td>";
                _mailBody += "<td align='center' style='background:#d5d5d5; color:F00; font-size:20px;'>";

                _mailBody += "<br/><strong>" + String.Format("{0:0,0.00}", Convert.ToSingle(_TotalVMI)) + "</strong>";
                _mailBody += "</td>";
                _mailBody += "</tr>";

                //CTPL
                if (_dtSeletectItem.Rows[0]["IsIncludeCMI"].ToString() == "True")
                {
                    //CMI
                    _mailBody += "<tr>";
                    _mailBody += "<td style='border-bottom:1px solid #ccc;' align='left' valign='bottom' ><strong>" + Resources.CarInsuranceResultPage.CTPL + "</strong></td>";
                    _mailBody += "<td align='center' style='background:#c5c5c5;'>";

                    _mailBody += "<br/><strong>" + String.Format("{0:0,0.00}", Convert.ToSingle(_TotalCMI)) + "</strong>";
                    _mailBody += "</td>";
                    _mailBody += "</tr>";

                    //Total
                    _mailBody += "<tr>";
                    _mailBody += "<td style='border-bottom:1px solid #ccc;' align='left' valign='bottom'><strong>" + Resources.CarInsuranceResultPage.Total + "</strong></td>";
                    _mailBody += "<td align='center' style='background:#d5d5d5; color:F00; font-size:20px;'>";
                    _mailBody += "<br/><strong>" + String.Format("{0:0,0.00}", Convert.ToSingle(_FinalAnnualPremiumNoDisc)) + "</strong>";
                }


                _mailBody += "<tr>";
                if (_strPaymentOption == "IP")
                {
                    _mailBody += "<td style='border-bottom:1px solid #ccc;'  align='left' valign='bottom'><strong>" + Resources.CarInsuranceResultPage.SpecialPrice + "</strong> (" + Resources.CarInsuranceResultPage.Valid7Days + ")</td>";
                }
                else
                {
                    _mailBody += "<td align='left' valign='bottom'><strong>" + Resources.CarInsuranceResultPage.SpecialPrice + "</strong> (" + Resources.CarInsuranceResultPage.Valid7Days + ")</td>";
                }
                _mailBody += "<td align='center' style='background:#c5c5c5; color:F00; font-size:20px;'>";
                _mailBody += "<br/><strong>" + String.Format("{0:0,0.00}", Convert.ToSingle(_FinalAnnualPremium)) + "</strong> ";

            }
            else
            {
                //FOR OLD QUOTATION - Temp
                #region BEFORE 28/Sep/2012
                //CTPL
                if (_dtSeletectItem.Rows[0]["IsIncludeCMI"].ToString() == "True")
                {
                    //premium before ctpl
                    _mailBody += "<tr>";
                    _mailBody += "<td align='left' ><strong>" + Resources.General.AnnualPremium + "</strong></td>";
                    _mailBody += "<td align='center' style='background:#d5d5d5; color:F00; font-size:20px;'>";


                   

                    float _newAnnualPremium = Convert.ToSingle(_FinalAnnualPremium) - Convert.ToSingle(_TotalCMI);

                    _mailBody += "<br/><strong>" + String.Format("{0:0,0.00}", Convert.ToSingle(_newAnnualPremium)) + "</strong>";
                    _mailBody += "</td>";
                    _mailBody += "</tr>";

                    //ctplamount
                    _mailBody += "<tr>";
                    _mailBody += "<td align='left' ><strong>" + Resources.CarInsuranceResultPage.CTPL + "</strong></td>";
                    _mailBody += "<td align='center' style='background:#d5d5d5;'>";

                    _mailBody += "<br/><strong>" + String.Format("{0:0,0.00}", Convert.ToSingle(_TotalCMI)) + "</strong>";
                    _mailBody += "</td>";
                    _mailBody += "</tr>";

                }

                //premium
                _mailBody += "<tr>";
                _mailBody += "<td align='left' ><strong>" + Resources.CarInsuranceResultPage.TotalVMI + "</strong></td>";
                _mailBody += "<td align='center' style='background:#d5d5d5; color:F00; font-size:20px;'>";

                if (_dtSeletectItem.Rows[0]["IsIncludeCMI"].ToString() == "False")
                {
                   
                    _mailBody += "<br/><strong>" + String.Format("{0:0,0.00}", Convert.ToSingle(_FinalAnnualPremium)) + "</strong>";
                }
                else
                {
                    _mailBody += "<br/><strong>" + String.Format("{0:0,0.00}", Convert.ToSingle(_FinalAnnualPremium)) + "</strong>";
                }
                #endregion
            }

            //Sakthi Change on 04 Dec 2012 -- Start
            if (_strPaymentOption == "IP")
            {
                _mailBody += "<tr>";
                _mailBody += "<td align='left' valign='bottom'><strong>" + Resources.CarInsurance.MonthlyInstallments + "</strong></td>";
                _mailBody += "<td align='center' style='background:#d5d5d5; color:F00; font-size:20px;'>";
                _mailBody += "<br/><strong>" + String.Format("{0:0,0.00}", Convert.ToSingle(_strMonthlyInstallment)) + "</strong> ";

                _mailBody += "<tr>";
                _mailBody += "<td align='left' valign='bottom'><strong>" + Resources.CarInsurance.InstallmentperMonth + "</strong></td>";
                _mailBody += "<td align='center' style='background:#d5d5d5; color:F00; font-size:20px;'>";
                _mailBody += "<br/><strong>" + _Installments.ToString() + " " + Resources.CarInsurance.Months + "</strong> ";

                _mailBody += "<tr>";
                _mailBody += "<td align='left' valign='bottom'><strong>" + Resources.CarInsurance.CreditCardby + "</strong></td>";
                _mailBody += "<td align='center' style='background:#d5d5d5; color:F00; font-size:20px;'>";
                _mailBody += "<br/><strong>" + GetBankName(_BankCode) + "</strong> ";

                _mailBody += "<tr>";
                _mailBody += "<td align='left' valign='bottom'><strong>" + Resources.CarInsurance.ZeroPercentInterestFree + "</strong></td>";
                _mailBody += "<td align='center' style='background:#d5d5d5; color:F00; font-size:20px;'>";
                _mailBody += "<br/><strong>" + _InerestFree + "</strong> ";

            }


            //Sakthi Change on 04 Dec 2012 -- End

            _mailBody += "</td>";
            _mailBody += "</tr>";


            _mailBody += "</table>";
            _mailBody += "<br/><br/>";
            _mailBody += "<u>" + Resources.Proposal.ForBankIn + "</u>";
            _mailBody += "<br/>" + Resources.Proposal.ForBankInMsg1;


            _mailBody += "<br/>";

            _mailBody += "<br/>" + Resources.Proposal.ForBankInMsg2;

            _mailBody += "<br/>";

            _mailBody += "<br/><strong>" + Resources.Proposal.Remarks + "</strong>";
            _mailBody += "<br/>" + Resources.Proposal.RemarksMsg1;
            _mailBody += "<br/>";
            _mailBody += "<br/><strong>" + Resources.Proposal.CompareXpress + "</strong>";
            _mailBody += "<br/>" + Resources.Proposal.CompareXpressAddress;


            _mailBody += "</td></tr>";
            _mailBody += "<tr><td id='email_footer'>";
            _mailBody += "</td></tr></table>";

            _mailBody += "<hr />";
            _mailBody += Resources.EmailMessage.Footer;
            _mailBody += "<br/>";
            _mailBody += "<br /><i>" + Resources.EmailMessage.NoReply + "</i>";
            _mailBody += "<hr />";
            _mailBody += "</center></body>";

            bool _mailStatus = false;

            string[] _fileList = new string[2];
            _fileList[0] = CE.Configuration.MyConfigurationManager.GetAppSettingValue("NonGGCCFilePath");
            _fileList[1] = CE.Configuration.MyConfigurationManager.GetAppSettingValue("NonGGKYCFormFilePath");
            if (Session[General.SMTPAccountName].ToString().Contains("gluaygluay.com"))
            {
                _mailStatus = MyMailManager.SendGGMailWithAttach(Session[General.SMTPAccountName].ToString(), Session[General.SMTPAuthCode].ToString(), _emailTo, _ccemail, _bccemail, _emailSubject + " (Ref No : " + _dtSeletectItem.Rows[0]["Info1"].ToString() + ") ", _mailBody, Session[General.SMTPReplyTo].ToString(), _fileList);
            }
            else if (Session[General.SMTPAccountName].ToString().Contains("gmail.com"))
            {
                _mailStatus = MyMailManager.SendGGMailWithAttach(Session[General.SMTPAccountName].ToString(), Session[General.SMTPAuthCode].ToString(), _emailTo, _ccemail, _bccemail, _emailSubject + " (Ref No : " + _dtSeletectItem.Rows[0]["Info1"].ToString() + ") ", _mailBody, Session[General.SMTPReplyTo].ToString(), _fileList);
            }
            else
            {
                _mailStatus = MyMailManager.SendGGMailWithAttach(Session[General.SMTPAccountName].ToString(), Session[General.SMTPAuthCode].ToString(), _emailTo, _ccemail, _bccemail, _emailSubject + " (Ref No : " + _dtSeletectItem.Rows[0]["Info1"].ToString() + ") ", _mailBody, Session[General.SMTPReplyTo].ToString(), _fileList);
            }

            if (_mailStatus)
            {
                _retVal = true;
            }
            else
            {
                _retVal = false;
            }
        }
        else
        {
            lblSendOrderConfirmationMessage.Text = "<br/>" + Resources.General.OrderConfirmationNoSelectedItem;
        }

        return _retVal;
    }

    private string GetBankName(string BankCode)
    {
        string _BankName = "";
        if (BankCode == "BKK")
        {
            _BankName = Resources.CarInsurance.BankBKK;
        }
        else if (BankCode == "KBANK")
        {
            _BankName = Resources.CarInsurance.BankK;
        }
        else if (BankCode == "KTC")
        {
            _BankName = Resources.CarInsurance.BankKTC;
        }
        else if (BankCode == "CITI")
        {
            _BankName = Resources.CarInsurance.BankCITI;
        }
        else if (BankCode == "AYA")
        {
            _BankName = Resources.CarInsurance.BankAYA;
        }
        else if (BankCode == "CTRL")
        {
            _BankName = Resources.CarInsurance.CentralCard;
        }
        else if (BankCode == "RBSN")
        {
            _BankName = Resources.CarInsurance.RobinsonCard;
        }
        else if (BankCode == "HPRO")
        {
            _BankName = Resources.CarInsurance.HomeproCard;
        }
        return _BankName;
    }

    protected void btnSendOrderConfirmation_Click(Object sender, EventArgs e)
    {
        lblSendOrderConfirmationMessage.Text = string.Empty;
        if (SendOrderConfirmation())
        {
            BrokerPremiumDB _premiumDB = new BrokerPremiumDB();

            
            if (_premiumDB.SaveQuotationEmail(Convert.ToInt32(txtCarId.Text),
                            Convert.ToInt64(txtCustomerId.Text),
                            Convert.ToInt64(Session[General.UserId].ToString()),
                            txtEditLicensePlate.Text,
                            txtConfirmEmail.Text, 3) > 0)
            {
                lblSendOrderConfirmationMessage.Text += "<br/>" + Resources.General.OrderConfirmationSent + " at " + dateTimeNow.ToString("dd/MMM/yyyy hh:mm tt");
            }
            else
            {
                lblSendOrderConfirmationMessage.Text += "<br/> " + Resources.General.OrderConfirmationSent + " Saving confirm email was failed.";
            }
        }
        else
        {
            lblSendOrderConfirmationMessage.Text += "<br/>" + Resources.General.OrderConfirmationFailed;
        }
    }

    protected void btnNewPremium_Click(object sender, EventArgs e)
    {
        ClearFields();
        if ((Convert.ToInt32(txtPremiumId.Text) > 0) || (Convert.ToInt32(txtPremiumId.Text) <= 0 && grvPremiumList.Rows.Count < 4))
        {
            lblPremiumError.Text = string.Empty;
            lblPremiumMessage.Text = string.Empty;
        }
        else
        {
            lblPremiumMessage.Text = string.Empty;
            lblPremiumError.Text = "Please create only Max 4 quotations!";
        }
    }

    private void LoadDiscountPercentageList()
    {
        //31	Chartis
        //46	Tokio Marine
        //41	Kurnia
        //35	KrungThai
        //33	MuangThai
        //32	BKI
        //29	LMG  Insurance
        //12	MSIG
        //11	Allianz CP
        //16	AXA

        DateTime _dtCoverCommDate = dateTimeNow;
        if (lblCoverCommencementDate.Text != string.Empty)
        {
            _dtCoverCommDate = Convert.ToDateTime(lblCoverCommencementDate.Text);
        }
        DateTime _dtThreeDayPlus = Convert.ToDateTime(dateTimeNow.AddDays(3).ToString("dd/MMM/yyyy"));
        DateTime _dtEditCoverCommDate = Convert.ToDateTime(lblEditCoverCommencementDate.Text);

        int _maxPercentage = 0;
        int _providerComId = Convert.ToInt32(ddlBrokerProvider.Text);

        //              ≤ 3 days	≥ 4 days
        // 16     AXA	    2%	        7%
        // 11     AZCP	    2%	        7%
        // 32     BKI	    2%	        7%
        // 31     CHARTIS	4%	        13%
        // 41     KURNIA	4%	        13%
        // 29     LMG	    4%	        11%
        // 12     MSIG	    4%	        13%
        // 33     MTI	    2%	        8%
        // 46     TOKIO	    2%	        5%
       
        if (_providerComId == 41 || divCompletedQuoteDetails.Visible == false)
        {
            if (DateTime.Compare(_dtThreeDayPlus, _dtEditCoverCommDate) > 0)
            {
                if (_providerComId == 16) //AXA
                {
                    _maxPercentage = 2;
                }
                else if (_providerComId == 11) // AZCP
                {
                    _maxPercentage = 2;
                }
                else if (_providerComId == 32) //BKI
                {
                    _maxPercentage = 2;
                }
                else if (_providerComId == 31) //CHARTIS
                {
                    _maxPercentage = 4;
                }
                else if (_providerComId == 41) //KURNIA
                {
                    _maxPercentage = 4;
                }
                else if (_providerComId == 29) //LMG
                {
                    _maxPercentage = 4;
                }
                else if (_providerComId == 12) //MSIG
                {
                    _maxPercentage = 4;
                }
                else if (_providerComId == 33) //MTI
                {
                    _maxPercentage = 2;
                }
                else if (_providerComId == 35) //KPI
                {
                    _maxPercentage = 2;
                }
                else if (_providerComId == 46) //TOKIO
                {
                    _maxPercentage = 2;
                }
            }
            else
            {
                if (_providerComId == 16) //AXA
                {
                    _maxPercentage = 7;
                }
                else if (_providerComId == 11) // AZCP
                {
                    _maxPercentage = 7;
                }
                else if (_providerComId == 32) //BKI
                {
                    _maxPercentage = 7;
                }
                else if (_providerComId == 31) //CHARTIS
                {
                    _maxPercentage = 13;
                }
                else if (_providerComId == 41) //KURNIA
                {
                    _maxPercentage = 13;
                }
                else if (_providerComId == 29) //LMG
                {
                    _maxPercentage = 11;
                }
                else if (_providerComId == 12) //MSIG
                {
                    _maxPercentage = 13;
                }
                else if (_providerComId == 33) //MTI
                {
                    _maxPercentage = 8;
                }
                else if (_providerComId == 35) //KPI
                {
                    _maxPercentage = 10;
                }
                else if (_providerComId == 46) //TOKIO
                {
                    _maxPercentage = 5;
                }
            }
        }
        else
        {
            _maxPercentage = 10;
        }

        //16 Jul 2012 to 30 Sep 2012 (9%)
        //01 Oct 2012 to 31 Dec 2012 (5%) - After 7 Days, 0%
        DateTime _dtStartDate = new DateTime(2012, 09, 01);
        DateTime _dtEndDate = new DateTime(2099, 12, 31);
        if (DateTime.Compare(dateTimeNow, _dtStartDate) > 0 && DateTime.Compare(dateTimeNow, _dtEndDate) < 0)
        {
            _maxPercentage = 5;

            if (chkCompanyStaff.Checked)
            {
                _maxPercentage = 15;// 12; Changed on 30 Nov 2012
            }

            if (_providerComId == 41 || _providerComId == 43) //KURNIA and SMK
            {
                ddlDiscountPercentage.Enabled = true;
            }

            //Sakthi on 02 Oct 2012 -- Start
            Int64 _PremiumId = 0;
            if (!Int64.TryParse(txtPremiumId.Text, out _PremiumId))
            {
                _PremiumId = 0;
            }
            if (_PremiumId > 0)
            {
                Int32 percert = _maxPercentage;
                DataSet _dsPremium = new DataSet();
                _dsPremium = GetBrokerPremiumbyPremiumId(_PremiumId);
                if (_dsPremium != null && _dsPremium.Tables.Count > 0 && _dsPremium.Tables[0].Rows.Count > 0)
                {
                    if (_dsPremium.Tables[0].Rows[0]["DiscountPercentage"] != DBNull.Value)
                    {
                        Int32.TryParse(_dsPremium.Tables[0].Rows[0]["DiscountPercentage"].ToString(), out percert);
                        if (percert > 0)
                        {
                            _maxPercentage = percert;
                        }
                    }
                }
            }
            //Sakthi on 02 Oct 2012 -- End
        }

        if (_providerComId == 41 && ddlBrokerCoverType.Text == "11")
        {
            _maxPercentage = 0;
        }


        ddlDiscountPercentage.Items.Clear();
        

        for (int i = _maxPercentage; i >= 0; i--)
        {
            ddlDiscountPercentage.Items.Add(new ListItem(i.ToString() + " " + "%", i.ToString()));
        }

        if (divCompletedQuoteDetails.Visible)
        {
            ddlDiscountPercentage.Text = _maxPercentage.ToString();
        }

        if (DateTime.Compare(dateTimeNow, _dtStartDate) > 0 && DateTime.Compare(dateTimeNow, _dtEndDate) < 0)
        {
            ddlDiscountPercentage.Text = _maxPercentage.ToString();
        }

        if (_providerComId == 41 || _providerComId == 43) //KURNIA and SMK
        {
            ddlDiscountPercentage.Text = "0";
        }

        ddlDiscountPercentage_SelectedIndexChanged(null, null);
    }

    //Sakthi on 02 Oct 2012 -- Start
    public DataSet GetBrokerPremiumbyPremiumId(Int64 CXBrokerPremiumId)
    {
        MyDatabase _db = new MyDatabase("GG_CRMDBConnectionString");
        SortedList _sPara = new SortedList();
        string _spName = "sprocCXBrokerPremiumDiscountPercentageSelectSingleItem";
        _sPara.Add("@CXBrokerPremiumId", CXBrokerPremiumId);
        DataSet _ds = new DataSet();
        return _ds = _db.GetDataSet(_spName, _sPara);
    }
    //Sakthi on 02 Oct 2012 -- End

    //Sakthi on 03 Oct 2012 -- Start

    private void LoadMonthlyInstallment()
    {
        ddlCreditCard.Items.Clear();
        ddlCreditCard.Items.Add(new ListItem(Resources.CarInsurance.Select, "-1"));

        ddlPaymentOption.Items.Clear();
        ddlPaymentOption.Items.Add(new ListItem(Resources.CarInsurance.Select, "-1"));
        ddlPaymentOption.Items.Add(new ListItem(Resources.CarInsurance.Installment, "IP"));
        ddlPaymentOption.Items.Add(new ListItem(Resources.CarInsurance.AnnualPayment, "FP"));

        if (ddlBrokerProvider.SelectedIndex > 0)
        {
            string IPDiscount = CE.Configuration.MyConfigurationManager.GetAppSettingValue("IPDiscount");
            lblInterest.Text = Resources.CarInsurance.InterestFree;
            if (ddlBrokerProvider.Text == "11")
            {
                ddlNoofInstallments.Items.Clear();
                ddlNoofInstallments.Items.Add(new ListItem("6" + " " + Resources.CarInsurance.Installment, "6"));
                ddlNoofInstallments.Items.Add(new ListItem("3" + " " + Resources.CarInsurance.Installment, "3"));

                ddlCreditCard.Items.Clear();
                ddlCreditCard.Items.Add(new ListItem(Resources.CarInsurance.BankCITI, "CITI"));
                ddlCreditCard.Items.Add(new ListItem(Resources.CarInsurance.BankK, "KBANK"));

                ddlGGDiscount.Items.Clear();
                ddlGGDiscount.Items.Add(new ListItem("0" + " %", "0"));
            }
            else if (ddlBrokerProvider.Text == "29")
            {
                ddlNoofInstallments.Items.Clear();
                ddlNoofInstallments.Items.Add(new ListItem("6" + " " + Resources.CarInsurance.Installment, "6"));
                ddlNoofInstallments.Items.Add(new ListItem("4" + " " + Resources.CarInsurance.Installment, "4"));
                ddlNoofInstallments.Items.Add(new ListItem("3" + " " + Resources.CarInsurance.Installment, "3"));

                ddlCreditCard.Items.Clear();
                ddlCreditCard.Items.Add(new ListItem(Resources.CarInsurance.BankBKK, "BKK"));
                ddlCreditCard.Items.Add(new ListItem(Resources.CarInsurance.BankKTC, "KTC"));
                ddlCreditCard.Items.Add(new ListItem(Resources.CarInsurance.BankK, "KBANK"));

                ddlGGDiscount.Items.Clear();
                if (IPDiscount != string.Empty)
                {
                    ddlGGDiscount.Items.Add(new ListItem(IPDiscount.ToString() + " %", IPDiscount.ToString()));
                }
                ddlGGDiscount.Items.Add(new ListItem("0" + " %", "0"));
            }
            else if (ddlBrokerProvider.Text == "32")
            {
                if (ddlBrokerCoverType.Text == "10" || ddlBrokerCoverType.Text == "11" || ddlBrokerCoverType.Text == "21")
                {
                    ddlNoofInstallments.Items.Clear();
                    ddlNoofInstallments.Items.Add(new ListItem("6" + " " + Resources.CarInsurance.Installment, "6"));
                    ddlNoofInstallments.Items.Add(new ListItem("3" + " " + Resources.CarInsurance.Installment, "3"));

                    ddlGGDiscount.Items.Clear();
                    ddlGGDiscount.Items.Add(new ListItem("0" + " %", "0"));
                }
                else
                {
                    ddlNoofInstallments.Items.Clear();
                    ddlNoofInstallments.Items.Add(new ListItem("0" + " " + Resources.CarInsurance.Installment, "0"));

                    ddlGGDiscount.Items.Clear();
                    ddlGGDiscount.Items.Add(new ListItem("0" + " %", "0"));


                    ddlPaymentOption.Items.Clear();
                    ddlPaymentOption.Items.Add(new ListItem(Resources.CarInsurance.Select, "-1"));
                    ddlPaymentOption.Items.Add(new ListItem(Resources.CarInsurance.AnnualPayment, "FP"));
                }

                ddlCreditCard.Items.Clear();
                ddlCreditCard.Items.Add(new ListItem(Resources.CarInsurance.BankBKK, "BKK"));
                ddlCreditCard.Items.Add(new ListItem(Resources.CarInsurance.BankCITI, "CITI"));
                ddlCreditCard.Items.Add(new ListItem(Resources.CarInsurance.BankKTC, "KTC"));
                ddlCreditCard.Items.Add(new ListItem(Resources.CarInsurance.BankAYA, "AYA"));
                ddlCreditCard.Items.Add(new ListItem(Resources.CarInsurance.CentralCard, "CTRL"));
                ddlCreditCard.Items.Add(new ListItem(Resources.CarInsurance.RobinsonCard, "RBSN"));
                ddlCreditCard.Items.Add(new ListItem(Resources.CarInsurance.HomeproCard, "HPRO"));
                ddlCreditCard.Items.Add(new ListItem(Resources.CarInsurance.BankK, "KBANK"));//Sakthi on 15 Nov 2012
            }
            else
            {
                ddlNoofInstallments.Items.Clear();
                ddlNoofInstallments.Items.Add(new ListItem("3" + " " + Resources.CarInsurance.Installment, "3"));

                ddlCreditCard.Items.Clear();
                ddlCreditCard.Items.Add(new ListItem(Resources.CarInsurance.BankK, "KBANK"));
            }
            ddlCreditCard_SelectedIndexChanged(null, null);
            NoofInstallments_SelectedIndexChanged(null, null);
        }
    }

    private void LoadBrokerDefault() //Sop Create method and updated on 16 Nov 2012 from BKK
    {
        try
        {
            MyDatabase _myDB = new MyDatabase();

            string _strSelect = "Select * from tblCXBrokerDefaultBenefits ";
            _strSelect = _strSelect + " WHERE CXBrokerProviderId = " + ddlBrokerProvider.Text;
            _strSelect = _strSelect + " AND GarageType = " + ddlGarageType.Text;
            _strSelect = _strSelect + " AND InsuranceType = " + ddlBrokerCoverType.SelectedValue;

            DataTable _dtDefaultValues = new DataTable("tblDefault");

            _dtDefaultValues = _myDB.GetDataTable(_strSelect);

            if (_dtDefaultValues != null && _dtDefaultValues.Rows.Count > 0)
            {
                if (_dtDefaultValues.Rows[0]["TPBIA"] != DBNull.Value)
                {
                    txtTPBIA.Text = Convert.ToInt32(_dtDefaultValues.Rows[0]["TPBIA"].ToString()).ToString("#,000");
                }

                if (_dtDefaultValues.Rows[0]["TPBIP"] != DBNull.Value)
                {
                    txtTPBIP.Text = Convert.ToInt32(_dtDefaultValues.Rows[0]["TPBIP"].ToString()).ToString("#,000");
                }

                if (_dtDefaultValues.Rows[0]["TPPD"] != DBNull.Value)
                {
                    txtTPPD.Text = Convert.ToInt32(_dtDefaultValues.Rows[0]["TPPD"].ToString()).ToString("#,000");
                }

                if (_dtDefaultValues.Rows[0]["PAPassenger"] != DBNull.Value)
                {
                    txtPA.Text = _dtDefaultValues.Rows[0]["PAPassenger"].ToString();
                }

                if (_dtDefaultValues.Rows[0]["MedicalExpense"] != DBNull.Value)
                {
                    txtMED.Text = _dtDefaultValues.Rows[0]["MedicalExpense"].ToString();
                }

                if (_dtDefaultValues.Rows[0]["BailBond"] != DBNull.Value)
                {
                    txtBailBond.Text = Convert.ToInt32(_dtDefaultValues.Rows[0]["BailBond"].ToString()).ToString("#,000");
                }


                if (_dtDefaultValues.Rows[0]["DEC"] != DBNull.Value)
                {
                    txtDeductible.Text = _dtDefaultValues.Rows[0]["DEC"].ToString();
                }
                if (_dtDefaultValues.Rows[0]["FireTheft"] != DBNull.Value)
                {
                    txtFireTheft.Text = _dtDefaultValues.Rows[0]["FireTheft"].ToString();
                }
                if (_dtDefaultValues.Rows[0]["FloodCover"] != DBNull.Value)
                {
                    txtFloodCoverAmount.Text = _dtDefaultValues.Rows[0]["FloodCover"].ToString();
                }
            }
        }
        catch (Exception Ex)
        {
            lblPremiumMessage.Text = Ex.Message;
        }
    }

    protected void NoofInstallments_SelectedIndexChanged(object sender, EventArgs e)
    {
        try
        {
            if (ddlBrokerProvider.Text == "29")
            {
                if (ddlCreditCard.Text != "KBANK")
                {
                    if (ddlNoofInstallments.Text == "4")
                    {
                        lblInterest.Text = "3.2 % " + Resources.CarInsurance.Interest;
                    }
                    else if (ddlNoofInstallments.Text == "6")
                    {
                        lblInterest.Text = "4.8 % " + Resources.CarInsurance.Interest;
                    }
                    else
                    {
                        lblInterest.Text = Resources.CarInsurance.InterestFree;
                    }
                }
                else
                {
                    lblInterest.Text = Resources.CarInsurance.InterestFree;
                }
            }
            txtGrossPremium_TextChanged(null, null);
        }
        catch (Exception Ex)
        {
        }
    }

    //Sakthi on 03 Oct 2012 -- End

    protected void ddlCreditCard_SelectedIndexChanged(object sender, EventArgs e)
    {
        try
        {
            if (ddlBrokerProvider.Text == "11")
            {
                if (ddlCreditCard.Text == "CITI")
                {
                    ddlNoofInstallments.Items.Clear();
                    ddlNoofInstallments.Items.Add(new ListItem("6" + " " + Resources.CarInsurance.Installment, "6"));
                    NoofInstallments_SelectedIndexChanged(null, null);//Sakthi on 25 Oct 2012 -- Added
                }
                else
                {
                    ddlNoofInstallments.Items.Clear();
                    ddlNoofInstallments.Items.Add(new ListItem("3" + " " + Resources.CarInsurance.Installment, "3"));
                    ddlNoofInstallments.Items.Add(new ListItem("4" + " " + Resources.CarInsurance.Installment, "4"));
                    ddlNoofInstallments.Items.Add(new ListItem("6" + " " + Resources.CarInsurance.Installment, "6"));
                    NoofInstallments_SelectedIndexChanged(null, null);//Sakthi on 25 Oct 2012 -- Added
                }
            }

            //For K Bank 6 Months Installments -- 22 Oct 2012 -- Start
            decimal _AnnualPremium = 0;
            decimal _AnnualPremiumWOD = 0;
            if (!decimal.TryParse(txtAnnualPremium.Text, out _AnnualPremium))
            {
                _AnnualPremium = 0;
            }
            if (!decimal.TryParse(txtFinalAnnualPremiumNoDisc.Text, out _AnnualPremiumWOD))
            {
                _AnnualPremiumWOD = 0;
            }
            if (_AnnualPremiumWOD >= 20000 && ddlCreditCard.Text == "KBANK")
            {
               
                if (ddlBrokerProvider.Text == "32")
                {
                    if (ddlBrokerCoverType.Text == "10" || ddlBrokerCoverType.Text == "11" || ddlBrokerCoverType.Text == "21")
                    {
                       
                        if (ddlNoofInstallments.Text == "3")
                        {
                            ddlNoofInstallments.Items.Clear();
                            ddlNoofInstallments.Items.Add(new ListItem("3" + " " + Resources.CarInsurance.Installment, "3"));
                            ddlNoofInstallments.Items.Add(new ListItem("6" + " " + Resources.CarInsurance.Installment, "6"));
                        }
                        else
                        {
                            ddlNoofInstallments.Items.Clear();
                            ddlNoofInstallments.Items.Add(new ListItem("6" + " " + Resources.CarInsurance.Installment, "6"));
                            ddlNoofInstallments.Items.Add(new ListItem("3" + " " + Resources.CarInsurance.Installment, "3"));
                        }
                       

                    }
                    else
                    {
                        ddlNoofInstallments.Items.Clear();
                        ddlNoofInstallments.Items.Add(new ListItem("0" + " " + Resources.CarInsurance.Installment, "0"));
                    }
                }
                else
                {
                    if (ddlNoofInstallments.Text == "3")
                    {
                        ddlNoofInstallments.Items.Clear();
                        ddlNoofInstallments.Items.Add(new ListItem("3" + " " + Resources.CarInsurance.Installment, "3"));
                        ddlNoofInstallments.Items.Add(new ListItem("6" + " " + Resources.CarInsurance.Installment, "6"));
                    }
                    else
                    {
                        ddlNoofInstallments.Items.Clear();
                        ddlNoofInstallments.Items.Add(new ListItem("6" + " " + Resources.CarInsurance.Installment, "6"));
                        ddlNoofInstallments.Items.Add(new ListItem("3" + " " + Resources.CarInsurance.Installment, "3"));
                    }
                }
                NoofInstallments_SelectedIndexChanged(null, null);
               
            }
            else
            {
                if (ddlBrokerProvider.Text == "11")
                {
                    if (ddlCreditCard.Text == "CITI")
                    {
                        ddlNoofInstallments.Items.Clear();
                        ddlNoofInstallments.Items.Add(new ListItem("6" + " " + Resources.CarInsurance.Installment, "6"));
                        NoofInstallments_SelectedIndexChanged(null, null);//Sakthi on 25 Oct 2012 -- Added
                    }
                    else if (ddlCreditCard.Text == "KBANK")
                    {
                        ddlNoofInstallments.Items.Clear();
                        ddlNoofInstallments.Items.Add(new ListItem("3" + " " + Resources.CarInsurance.Installment, "3"));
                        NoofInstallments_SelectedIndexChanged(null, null);
                    }
                }
                else if (ddlBrokerProvider.Text == "29")
                {
                    if (ddlCreditCard.Text == "KBANK")
                    {
                        ddlNoofInstallments.Items.Clear();
                        ddlNoofInstallments.Items.Add(new ListItem("3" + " " + Resources.CarInsurance.Installment, "3"));
                        NoofInstallments_SelectedIndexChanged(null, null);
                    }
                    else if (ddlNoofInstallments.Text == "6")
                    {
                        ddlNoofInstallments.Items.Clear();
                        ddlNoofInstallments.Items.Add(new ListItem("6" + " " + Resources.CarInsurance.Installment, "6"));
                        ddlNoofInstallments.Items.Add(new ListItem("4" + " " + Resources.CarInsurance.Installment, "4"));
                        NoofInstallments_SelectedIndexChanged(null, null);
                    }
                    else
                    {
                        ddlNoofInstallments.Items.Clear();
                        ddlNoofInstallments.Items.Add(new ListItem("4" + " " + Resources.CarInsurance.Installment, "4"));
                        ddlNoofInstallments.Items.Add(new ListItem("6" + " " + Resources.CarInsurance.Installment, "6"));
                        NoofInstallments_SelectedIndexChanged(null, null);
                    }
                }
                else if (ddlBrokerProvider.Text == "32")
                {
                    if (ddlBrokerCoverType.Text == "10" || ddlBrokerCoverType.Text == "11" || ddlBrokerCoverType.Text == "21")
                    {
                       
                        if (ddlCreditCard.Text == "KBANK")
                        {
                            ddlNoofInstallments.Items.Clear();
                            ddlNoofInstallments.Items.Add(new ListItem("3" + " " + Resources.CarInsurance.Installment, "3"));
                            NoofInstallments_SelectedIndexChanged(null, null);
                        }
                        else
                        {
                            ddlNoofInstallments.Items.Clear();
                            ddlNoofInstallments.Items.Add(new ListItem("6" + " " + Resources.CarInsurance.Installment, "6"));
                            NoofInstallments_SelectedIndexChanged(null, null);
                        }
                       
                    }
                    else
                    {
                        ddlNoofInstallments.Items.Clear();
                        ddlNoofInstallments.Items.Add(new ListItem("0" + " " + Resources.CarInsurance.Installment, "0"));
                        NoofInstallments_SelectedIndexChanged(null, null);//Sakthi on 25 Oct 2012 -- Added
                    }
                }
                else
                {
                    ddlNoofInstallments.Items.Clear();
                    ddlNoofInstallments.Items.Add(new ListItem("3" + " " + Resources.CarInsurance.Installment, "3"));
                    NoofInstallments_SelectedIndexChanged(null, null);//Sakthi on 25 Oct 2012 -- Added
                }
            }

            
        }
        catch (Exception Ex)
        {
        }
    }

    //Sakthi on 25 Oct 2012 -- Start
    public void SixMonthIstallMents()
    {
        //For K Bank 6 Months Installments -- 22 Oct 2012 -- Start
        decimal _AnnualPremium = 0;
        decimal _AnnualPremiumWOD = 0;
        if (!decimal.TryParse(txtAnnualPremium.Text, out _AnnualPremium))
        {
            _AnnualPremium = 0;
        }
        if (!decimal.TryParse(txtFinalAnnualPremiumNoDisc.Text, out _AnnualPremiumWOD))
        {
            _AnnualPremiumWOD = 0;
        }
        if (_AnnualPremiumWOD >= 20000 && ddlCreditCard.Text == "KBANK")
        {
            
            if (ddlBrokerProvider.Text == "32")
            {
                if (ddlBrokerCoverType.Text == "10" || ddlBrokerCoverType.Text == "11" || ddlBrokerCoverType.Text == "21")
                {
                    //Sakthi on 06 Nov 2012 -- Start
                    if (ddlNoofInstallments.Text == "3")
                    {
                        ddlNoofInstallments.Items.Clear();
                        ddlNoofInstallments.Items.Add(new ListItem("3" + " " + Resources.CarInsurance.Installment, "3"));
                        ddlNoofInstallments.Items.Add(new ListItem("6" + " " + Resources.CarInsurance.Installment, "6"));
                    }
                    else
                    {
                        ddlNoofInstallments.Items.Clear();
                        ddlNoofInstallments.Items.Add(new ListItem("6" + " " + Resources.CarInsurance.Installment, "6"));
                        ddlNoofInstallments.Items.Add(new ListItem("3" + " " + Resources.CarInsurance.Installment, "3"));
                    }
                    
                }
                else
                {
                    ddlNoofInstallments.Items.Clear();
                    ddlNoofInstallments.Items.Add(new ListItem("0" + " " + Resources.CarInsurance.Installment, "0"));
                }
            }
            else
            {
                if (ddlNoofInstallments.Text == "3")
                {
                    ddlNoofInstallments.Items.Clear();
                    ddlNoofInstallments.Items.Add(new ListItem("3" + " " + Resources.CarInsurance.Installment, "3"));
                    ddlNoofInstallments.Items.Add(new ListItem("6" + " " + Resources.CarInsurance.Installment, "6"));
                }
                else
                {
                    ddlNoofInstallments.Items.Clear();
                    ddlNoofInstallments.Items.Add(new ListItem("6" + " " + Resources.CarInsurance.Installment, "6"));
                    ddlNoofInstallments.Items.Add(new ListItem("3" + " " + Resources.CarInsurance.Installment, "3"));
                }
            }
            
        }
        else
        {
            if (ddlBrokerProvider.Text == "11")
            {
                if (ddlCreditCard.Text == "CITI")
                {
                    ddlNoofInstallments.Items.Clear();
                    ddlNoofInstallments.Items.Add(new ListItem("6" + " " + Resources.CarInsurance.Installment, "6"));
                }
                else
                {
                    ddlNoofInstallments.Items.Clear();
                    ddlNoofInstallments.Items.Add(new ListItem("3" + " " + Resources.CarInsurance.Installment, "3"));
                }
            }
            else if (ddlBrokerProvider.Text == "29")
            {
                if (ddlCreditCard.Text == "KBANK")
                {
                    ddlNoofInstallments.Items.Clear();
                    ddlNoofInstallments.Items.Add(new ListItem("3" + " " + Resources.CarInsurance.Installment, "3"));
                }
                else if (ddlNoofInstallments.Text == "6")
                {
                    ddlNoofInstallments.Items.Clear();
                    ddlNoofInstallments.Items.Add(new ListItem("6" + " " + Resources.CarInsurance.Installment, "6"));
                    ddlNoofInstallments.Items.Add(new ListItem("4" + " " + Resources.CarInsurance.Installment, "4"));
                }
                else
                {
                    ddlNoofInstallments.Items.Clear();
                    ddlNoofInstallments.Items.Add(new ListItem("4" + " " + Resources.CarInsurance.Installment, "4"));
                    ddlNoofInstallments.Items.Add(new ListItem("6" + " " + Resources.CarInsurance.Installment, "6"));
                }
            }
            else if (ddlBrokerProvider.Text == "32")
            {
                if (ddlBrokerCoverType.Text == "10" || ddlBrokerCoverType.Text == "11" || ddlBrokerCoverType.Text == "21")
                {
                    
                    if (ddlCreditCard.Text == "KBANK")
                    {
                        ddlNoofInstallments.Items.Clear();
                        ddlNoofInstallments.Items.Add(new ListItem("3" + " " + Resources.CarInsurance.Installment, "3"));
                    }
                    else
                    {
                        ddlNoofInstallments.Items.Clear();
                        ddlNoofInstallments.Items.Add(new ListItem("6" + " " + Resources.CarInsurance.Installment, "6"));
                    }
                   
                }
                else
                {
                    ddlNoofInstallments.Items.Clear();
                    ddlNoofInstallments.Items.Add(new ListItem("0" + " " + Resources.CarInsurance.Installment, "0"));
                }
            }
            else
            {
                ddlNoofInstallments.Items.Clear();
                ddlNoofInstallments.Items.Add(new ListItem("3" + " " + Resources.CarInsurance.Installment, "3"));
            }
        }

        
    }
  

    private void IncludeScripeEnable(string Language)
    {
        Int32 UserCampaign = 400;
        if (Session[CE.Global.General.UserCampaign] != null)
        {
            if (!Int32.TryParse(Session[CE.Global.General.UserCampaign].ToString(), out UserCampaign))
            {
                UserCampaign = 400;
            }
        }

        if (Language == "en-US")
        {
            if (UserCampaign == 1001)
            {
                divENScript.Visible = false;
                divTHScript.Visible = false;
                divOffENScript.Visible = true;
                divOffTHScript.Visible = false;
            }
            else
            {
                divENScript.Visible = true;
                divTHScript.Visible = false;
                divOffENScript.Visible = false;
                divOffTHScript.Visible = false;
            }
        }
        else
        {
            if (UserCampaign == 1001)
            {
                divTHScript.Visible = false;
                divENScript.Visible = false;
                divOffTHScript.Visible = true;
                divOffENScript.Visible = false;
            }
            else
            {
                divTHScript.Visible = true;
                divENScript.Visible = false;
                divOffTHScript.Visible = false;
                divOffENScript.Visible = false;
            }
        }
    }

    protected void csvDeductibleValid_ServerValidate(object source, ServerValidateEventArgs args)
    {
        args.IsValid = true;
        float _deductible = 0.0f;
        if (ddlBrokerProvider.Text == "43" && ddlBrokerCoverType.Text == "31" && txtUserTypeId.Text == "1001")
        {
            if (txtDeductible.Text.Trim() != "")
            {
                if (!float.TryParse(txtDeductible.Text, out _deductible))
                {
                    _deductible = 0.0f;
                }
                if (_deductible > 0)
                {
                    args.IsValid = true;
                }
                else
                {
                    args.IsValid = false;
                }
            }
            else
            {
                args.IsValid = false;
            }
        }
    }

  

}
